object Collection Containing a List of IDs Linq - vb.net

I have a list box and the user is able to multi-select. I want to use Linq and bring back the records of the selected IDs that the user selects. I need to bring back the full object record for each selected ID
Here is the contact object along with collection object
Namespace MODEL
<System.Serializable()> _
Public Class ContactCollection
Inherits System.Collections.ObjectModel.Collection(Of Contact)
Implements IList(Of Contact)
End Class
End Namespace
Namespace MODEL
<System.Serializable()> _
Public Class Contact
Private mContactID As Int32 = 0
Private mFirstName As String
Private mLastName As String
Public Property ContactID As Int32
Get
Return mContactID
End Get
Set(value As Int32)
mContactID = value
End Set
End Property
Public Property FirstName As String
Get
Return mFirstName
End Get
Set(value As String)
mFirstName = value
End Set
End Property
Public Property LastName As String
Get
Return mLastName
End Get
Set(value As String)
mLastName = value
End Set
End Property
End Class
End Namespace
Adding 5 Records to the collection object
Dim objCollection As New MODEL.ContactCollection
Dim obj As New MODEL.Contact
objCollection.Add(New MODEL.Contact With {
.ContactID = 1, _
.FirstName = "John", _
.LastName = "Smtih" _
})
objCollection.Add(New MODEL.Contact With {
.ContactID = 2, _
.FirstName = "Mark", _
.LastName = "Davis" _
})
objCollection.Add(New MODEL.Contact With {
.ContactID = 3, _
.FirstName = "Tom", _
.LastName = "Howe" _
})
objCollection.Add(New MODEL.Contact With {
.ContactID = 4, _
.FirstName = "Jerry", _
.LastName = "Thomas" _
})
objCollection.Add(New MODEL.Contact With {
.ContactID = 5, _
.FirstName = "Jane", _
.LastName = "Marry" _
})
This is the selected contact List from the list box
Dim lstContacts As New List(Of Integer)
lstContacts.Add(2)
lstContacts.Add(4)
I am not sure what to do at this point with Linq to find the values. I think I have to use contains but I have tried may different ways but I was unable to get the values.
I have tried this Linq but does not work or bring any records back
Dim objSearch from SearchContacts in objCollection
Where (lstContacts.Contains(SearchContacts.ContactID))

To get the Ids, try that :
Dim ids As IEnumerable(Of Int32) = myListBox.SelectedItems _
.OfType(Of Contact)() _
.Select( Function(c) c.ContactID ) _
Edit
If you want the Contacts, you can just just :
Dim ids As IEnumerable(Of Contact) = myListBox.SelectedItems _
.OfType(Of Contact)()
And if you want the contacts in a separate copied collection, you can :
Dim ids As List(Of Contact) = myListBox.SelectedItems _
.OfType(Of Contact)() _
.ToList()
Last (if think this is your real question - just tell and I erase everything above)
Dim selectedContacts As IEnumerable(Of MODEL.Contact) = From contact In objCollection
Join id In lstContacts
On contact.ContactID Equals id
Select contact

Related

Placing a collection of values into a For...each loop

I have this code written to return a collection of an object with properties as follows:
Public Shared Function Create() As Collection(Of Element)
Return New Collection(Of Element)() From { _
New Element() With { _
.Group = 1, _
.Period = 1, _
.Name = "Hydrogen" _
}, _
New Element() With { _
.Group = 18, _
.Period = 1, _
.Name = "Helium" _
}, _
New Element() With { _
.Group = 1, _
.Period = 2, _
.Name = "Lithium" _
}
}
End Function
I would now like to get these values from a database, but I can't figure out how to reformat the code. My returning procedure should be something like this:
Public Shared Function CreateDB() As Collection(Of Element)
Using db As New DataClassesDataContext(ACCCon)
Dim rows = (From row In db.PeriodicTableQs
Order By row.ID
Select row).ToList()
For Each s In rows
<<collect the elements here as result>>
<<eg, New Element() With {.Group = s.Group}>>
Next
End Using
Return Result
End Function
Thanks!
Try this:
Public Shared Function CreateDB() As Collection(Of Element)
Dim ACCCon As String = "ConnectionString"
Using db As New DataClassesDataContext(ACCCon)
Dim List = db.PeriodicTableQs.
OrderBy(Function(Q) Q.ID).ToList.
Select(Function(row)
Return New Element With {
.Group = row.Group,
.Name = row.Name,
.Period = row.Period
}
End Function)
End Using
Return New Collection(Of Element)(List)
End Function

How to return from ienumerable function in vb.net

Public Shared Function GetDataSet() As IEnumerable(Of SerialData)
Dim sCon As New SQLConnect
Dim strsql As String
Dim p As New Control
sCon.sqlAdp = New SqlDataAdapter
strsql = "select serialid," & _
" serialno," & _
" serialdesc," & _
" b.materialname," & _
" b.drawing," & _
" a.workorder," & _
" isnull((select top 1 patno from patternmaster where patid = a.patid),'Not Defined') as patno," & _
" case when a.activeflag = 1 then 'True' else 'False' end as activeflag" & _
" from serialmaster a," & _
" materialmaster b" & _
" where 1 = 1" & _
" and a.materialid = b.materialid" & _
" and b.activeflag = 1"
sCon.sqlCmd.CommandText = strsql
sCon.sqlAdp.SelectCommand = sCon.sqlCmd
sCon.sqlAdp.Fill(sCon.DS, "Listing")
Dim dtTable As DataTable
dtTable = sCon.DS.Tables("Listing")
' For Each row As DataRow In dtTable.Rows
' Return dtTable.AsEnumerable().[Select](Function(row) New With { _
' Key .serialid = row("serialid"), _
' Key .serialno = row("serialno"), _
' Key .serialdesc = row("serialdesc"), _
' Key .materialname = row("materialname"), _
' Key .drawing = row("drawing"), _
' Key .workorder = row("workorder"), _
' Key .patno = row("patno") _
'})
' Next
For Each row As DataRow In dtTable.Rows
p.serialid.Add(row("serialid"))
p.serialno.Add(row("serialno"))
p.serialdesc.Add(row("serialdesc"))
p.materialname.Add(row("materialname"))
p.drawing.Add(row("drawing"))
p.workorder.Add(row("workorder"))
p.patno.Add(row("patno"))
Next
Return p
End Function
Control class:
Public Class Control
Public serialid As New Generic.List(Of String)
Public serialno As New Generic.List(Of String)
Public serialdesc As New Generic.List(Of String)
Public materialname As New Generic.List(Of String)
Public drawing As New Generic.List(Of String)
Public workorder As New Generic.List(Of String)
Public patno As New Generic.List(Of String)
Public result As New Generic.List(Of String)
End Class
ServerSidePro class:
Public Class ServerSidePro
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim d As New Control
' Those parameters are sent by the plugin
Dim iDisplayLength = Integer.Parse(context.Request("iDisplayLength"))
Dim iDisplayStart = Integer.Parse(context.Request("iDisplayStart"))
Dim iSortCol = Integer.Parse(context.Request("iSortCol_0"))
Dim iSortDir = context.Request("sSortDir_0")
'Fetch the data from a repository (in my case in-memory)
'Dim p = SerialData.GetDataSet()
Dim p = DirectCast(SerialData.GetDataSet(), IEnumerable(Of SerialData))
' prepare an anonymous object for JSON serialization
Dim aaData2 = p.select(Function(h) New With {h.serialid, h.serialno, h.serialdesc, _
h.materialname, h.drawing, h.workorder, h.patno}).Skip(iDisplayStart).Take(iDisplayLength)
Dim str As New List(Of String())
For Each item In aaData2
Dim arr As String() = New String(6) {item.serialid, item.serialno, item.serialdesc, _
item.materialname, item.drawing, item.workorder, item.patno}
str.Add(arr)
Next
Dim result = New With { _
Key .iTotalRecords = p.Count(), _
Key .iTotalDisplayRecords = p.Count(), _
Key .aaData = str
}
Dim serializer As New JavaScriptSerializer()
Dim json = serializer.Serialize(result)
context.Response.ContentType = "application/json"
context.Response.ClearHeaders()
context.Response.Write(json)
context.Response.End()
'Return d
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
How to return dataset from this function it is giving error Unable to cast object of type 'Control' to type 'System.Collections.Generic.IEnumerable'.
Easiest way is to use a List() object. I would restructure your class
Public Class Control
Public LControl As New List(Of Control)
Public serialid As String
Public serialno As String
Public serialdesc As String
Public materialname As String
Public drawing As String
Public workorder As String
Public patno As String
Public result As String
End Class
​

Create own data examples in LinqPad

I have a class (vb.net) with some data that I want to query in LinqPad. I already worked with some examples as the one from "Linq in Action" so they work with some kind of classes with data as well to explain queries. But I just cannot find anything about how to import or write your own classes. Could anyone help me here?
My Class looks like:
Public Class Employee
Public Property ID As Integer
Public Property Salery As Integer
Public Property Name As String
Public Property Department As String
Public Property Gender As String
Public Shared Function GetAllEmployees() As List(Of Employee)
Return New List(Of Employee) From { _
New Employee With {.ID = 1, .Name = "Mark", .Department = "HR", .Gender = "Male", .Salery = 12000},
New Employee With {.ID = 2, .Name = "Sandra", .Department = "IT", .Gender = "Female", .Salery = 2000} _
}
End Function
End Class
You might be missing a couple things about using LINQPad:
Set the Language to "VB Program" and put classes where the comment says to.
Use the Dump method to output an expression. (For "VB Expression", Dump is called automatically.)
Here is an example. (Note, you might be using that SQL-looking syntax.)
Sub Main
Employee.GetAllEmployees() _
.Where(Function (employee) employee.Department = "HR") _
.Dump()
Dim hrEmployees = From employee In Employee.GetAllEmployees()
Where employee.Department = "HR"
hrEmployees.Dump()
End Sub
' Define other methods and classes here
Public Class Employee
Public Property ID As Integer
Public Property Salery As Integer
Public Property Name As String
Public Property Department As String
Public Property Gender As String
Public Shared Function GetAllEmployees() As List(Of Employee)
Return New List(Of Employee) From { _
New Employee With {.ID = 1, .Name = "Mark", .Department = "HR", .Gender = "Male", .Salery = 12000},
New Employee With {.ID = 2, .Name = "Sandra", .Department = "IT", .Gender = "Female", .Salery = 2000} _
}
End Function
End Class

'Order by' ignored in LINQ query

I am trying to sort a list by company name. I have tried the following code but this sorts the list by CompID and not CoShort. How should I change this to sort by CoShort?
Public Shared Function [SelectCompanyData](iElement() As Integer) As List(Of CompanyList)
Dim db As New EntryDataContext()
Dim q As IQueryable(Of CompanyList) = (From Act_Sub_Manfu_Link In db.Act_Sub_Manfu_Links _
Join Company In db.Companies _
On Act_Sub_Manfu_Link.CompID Equals Company.CompID _
Where iElement.Contains(Act_Sub_Manfu_Link.ACCN) _
And Company.In_Dir _
Select New CompanyList With { _
.CompID = Company.CompID, _
.InDir = Company.In_Dir, _
.CoShort = Company.CoShort _
}).Distinct
q.OrderBy(Function(c) c.CoShort)
Dim list As List(Of CompanyList) = q.ToList
Return list
End Function
You have to assign ordered collection into a variable:
Dim oq As IOrderedQueryable(Of CompanyList) = q.OrderBy(Function(c) c.CoShort)
And use it to get List of results:
Dim list As List(Of CompanyList) = oq.ToList()
Doesn't need to be assigned to anything but the return value
Public Function SelectCompanyData(iElement() As Integer) As List(Of CompanyList)
Dim db As New EntryDataContext()
Return (From Act_Sub_Manfu_Link In db.Act_Sub_Manfu_Links _
Join Company In db.Companies _
On Act_Sub_Manfu_Link.CompID Equals Company.CompID _
Where iElement.Contains(Act_Sub_Manfu_Link.ACCN) _
And Company.In_Dir _
Select New CompanyList With { _
.CompID = Company.CompID, _
.InDir = Company.In_Dir, _
.CoShort = Company.CoShort _
}).Distinct().OrderBy(Function(c) c.CoShort).ToList()
End Function

Linq to objects

I have 2 databases from different servers. I cannot link the databases. The data is retrieved from the databases as :
DB1
- Client_ID Engagement_ID Enabled Description
600 10 True Company1
600 20 False Company2
700 10 True Company3
DB2
Client_ID Engagement_ID Enabled
Description
600 5 True Company1
600 10 False Company2
500 30 True Company3
The T SQL for this task is:
select * from DB1
left join DB2 on DB1.client_ID = DB2.client_ID
and DB1.Engagement_ID = DB2.Engagement_ID
where DB2.CLient_ID is null
and DB2.Engagement_ID is null and DB1.client_id in (select client_id from DB2)
I need to do this VB.NET LINQ
The sample data you provided won't return any values anyway since they ClientId and EngagementId all have values.
I split the LINQ into two lists. I have yet to test this out or optimize it, but maybe this is what you're looking for to at least get you started.
Here is my attempt:
Public Class DBObject
Public Sub New(ByVal cId As Integer, _
ByVal eId As Integer, _
ByVal enabled As Boolean, _
ByRef desc As String)
_clientId = cId
_engagementId = eId
_enabled = enabled
_description = desc
End Sub
Private _clientId As Integer
Public Property ClientId() As Integer
Get
Return _clientId
End Get
Set(ByVal value As Integer)
_clientId = value
End Set
End Property
Private _engagementId As Integer
Public Property EngagementId() As Integer
Get
Return _engagementId
End Get
Set(ByVal value As Integer)
_engagementId = value
End Set
End Property
Private _enabled As Boolean
Public Property Enabled() As Boolean
Get
Return _enabled
End Get
Set(ByVal value As Boolean)
_enabled = value
End Set
End Property
Private _description As String
Public Property Description() As String
Get
Return _description
End Get
Set(ByVal value As String)
_description = value
End Set
End Property
End Class
Dim DB1 As New List(Of DBObject)
Dim DB2 As New List(Of DBObject)
DB1.Add(New DBObject(600, 10, True, "Company1"))
DB1.Add(New DBObject(600, 20, False, "Company2"))
DB1.Add(New DBObject(700, 10, True, "Company3"))
DB2.Add(New DBObject(600, 5, True, "Company1"))
DB2.Add(New DBObject(600, 10, False, "Company2"))
DB2.Add(New DBObject(500, 30, True, "Company3"))
Dim list1 As List(Of DBObject) = (From obj1 As DBObject In DB1 _
Join obj2 As DBObject In DB2 _
On obj1.ClientId Equals obj2.ClientId _
And obj1.EngagementId Equals obj2.EngagementId _
Where obj2.ClientId = Nothing _
And obj2.EngagementId = Nothing _
Select obj1).ToList
Dim list2 As List(Of DBObject) = (From obj3 As DBObject In list1 _
From obj4 As DBObject In DB2 _
Where obj3.ClientId = obj4.ClientId _
Select obj3).ToList
' list2 would have the results you desire
Dim list1 = From obj1 As DBObject In DB1 _
Group Join obj2 As DBObject In DB2 _
On obj1.ClientId Equals obj2.ClientId _
And obj1.EngagementId Equals obj2.EngagementId _
Into g = Group _
From r In g.DefaultIfEmpty() _
Where g.ElementAtOrDefault(0) Is Nothing _
Select New With {.Cl_ID = obj1.ClientId, .EngID = bj1.EngagementId}
Dim list2 = (From obj3 In list1 _
From obj4 In DB2 _
Where obj3.Cl_ID = obj4.ClientId _
Select obj3).Distinct.DefaultIfEmpty
I modified sunpech's code and List2 contains the expected result i.e. the second row of DB1 - 600, 20, False, "Company2"