Conversion Linq result to object type in vb.net - vb.net

I need vb.net syntax of below answer(given in c#)-
How can I convert Linq results to DTO class object without iteration
I have tried converting to vb.net at this link, but it does give compilation errors.
Following is the output from above convertor -
Public Function [Get]() As List(Of User)
Using db = New MyContext()
Return (From u In db.UsersOrder By u.FirstNameNew User() With { _
Key .Id = u.pkUser, _
Key .Username = u.Username, _
Key .Password = u.Password, _
Key .Active = u.Active _
}).ToList()
End Using
End Function

Well, the Linq query is obviously messed up. And since there's no User class in the code you tried to convert, the converter tried to use the Key keyword, which is only used for anonymous types.
So the correct code should look like:
Public Function [Get]() As List(Of User)
Using db = New MyContext()
Return (From u In db.Users
Order By u.FirstName
Select New User() With {
.Id = u.pkUser,
.Username = u.Username,
.Password = u.Password,
.Active = u.Active
}).ToList()
End Using
End Function
assuming the following User class:
Public Class User
Public Id As Integer
Public Username As String
Public Password As String
Public Active As Boolean
End Class

It worked now -
Following are the keyword were missing in convertor.
Order
Select New
removed keyword Key
and final code is as below -
Public Function [Get]() As List(Of User)
Using db = New MyContext()
Return (From u In db.UsersOrder Order By u.FirstNameNew select new User() With { _
.Id = u.pkUser, _
.Username = u.Username, _
.Password = u.Password, _
.Active = u.Active _
}).ToList()
End Using

Related

using csvhelper writer with shouldquote in vb.net

I can see how shouldquote works with c# but does anyone have an example in vb.net?
I need to wrap every field with chr(34)
Private Sub Main()
Dim records = New List(Of Foo) From {
New Foo With {
.Id = 1,
.Name = "one"
}
}
Dim config = New CsvConfiguration(CultureInfo.InvariantCulture) With {
.ShouldQuote = Function(args) True
}
Using csv = New CsvWriter(Console.Out, config)
csv.WriteRecords(records)
End Using
End Sub
Public Class Foo
Public Property Id As Integer
Public Property Name As String
End Class

object Collection Containing a List of IDs Linq

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

Left Outer Join doesnt show empty elements

I try to perform an left outer join within linq. My Datasource is:
Public Class Department
Public Property ID As Integer
Public Property Name As String
Public Shared Function GetAllDepartments() As List(Of Department)
Return New List(Of Department) From { _
New Department With {.ID = 1, .Name = "IT"},
New Department With {.ID = 2, .Name = "HR"},
New Department With {.ID = 3, .Name = "Payroll"}
}
End Function
End Class
Public Class Employee
Public Property ID As Integer
Public Property Name As String
Public Property DepartmentID As Integer
Public Shared Function GetAllEmployees() As List(Of Employee)
Return New List(Of Employee) From { _
New Employee With {.ID = 1, .Name = "Mark", .DepartmentID = 1},
New Employee With {.ID = 10, .Name = "Andy"}
}
End Function
End Class
My query is:
'Left Outer Join
Dim result = From emp In Employee.GetAllEmployees
Group Join dep In Department.GetAllDepartments
On emp.DepartmentID Equals dep.ID Into eGroup = Group
From all In eGroup.DefaultIfEmpty
Select New With {
.Person = emp.Name,
.DepartmentName = If(all.Name Is Nothing, "No Department", all.Name)}
What I expect to get is:
Mark IT
Andy No Department
But what I get is
Mark IT
Could anyone tell me, what is wrong with the query? I just cannot see it, even after reading msdn help for it over again, I just cannot find what is wrong.
I cannot reproduce this behavior because when I try to run your code it throws a NullReferenceException.
However, if I change this code:
.DepartmentName = If(all.Name Is Nothing, "No Department", all.Name)}
To this code:
.DepartmentName = If((all Is Nothing), "No Department", all.Name)}
I get the expected output:
Mark, ITAndy, No Department

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

Return a collection of model as an output

I am simply trying to create an function to return a set of user. But, in order to be able to add the item later to a collection I used arrayList, but at last I am getting an error of Type ArrayList cannot be converted to 1-Dimensional array of Users
Here is my Code:
Function getDoctorsList() As Users()
Dim userCollection As New ArrayList
Dim sql = "SELECT * FROM '" + _tblName + "' WHERE usertype = 'doctor'"
Dim dr As SqlDataReader = dbHelper.ExecuteAndGetReader(sql)
While dr.Read
Dim user As New Users
user.Id = IIf(IsDBNull(dr("id")), 0, dr("id"))
user.UserName = IIf(IsDBNull(dr("username")), "", dr("username"))
user.UserNin = IIf(IsDBNull(dr("user_nin")), 0, dr("user_nin"))
user.UserType = IIf(IsDBNull(dr("usertype")), "", dr("usertype"))
user.Password = IIf(IsDBNull(dr("password")), "", dr("password"))
userCollection.Add(user)
End While
Return userCollection
End Function
How to solve such problems?
Either let your method return an ArrayList:
Function getDoctorsList() As ArrayList()
create an Array out of your ArrayList:
Return userCollection.ToArray()
or, the best solution, let your method return an IEnumerable(Of User)
Function getDoctorsList() As IEnumerable(Of User)
you should also use a List(of User) instead of a ArrayList instead, since it is type safe (and clearer) and it also implements IEnumerable(Of User).
Edit
Example using IEnumerable(of Users) and DataRowExtensions:
Function GetDoctorsList() As IEnumerable(of Users)
Dim sql = "SELECT * FROM '" + _tblName + "' WHERE usertype = 'doctor'"
Dim table = new DataTable()
table.Load(dbHelper.ExecuteAndGetReader(sql))
Return (from row in table.AsEnumerable()
select new User() With
{
.Id = row.FieldOf(Of Integer)("id"),
.UserName = row.Field(Of String)("username"),
.UserNin = row.Field(Of Integer)("user_nin"),
.UserType = row.Field(Of String)("usertype"),
.Password = row.Field(Of String)("password")
}).ToList()
End Function