How to convert DataTable to Generic List using LINQ in VB.Net?

Posted by Rajnilari2015 under VB.NET category on | Points: 40 | Views : 612
Let us create a datatable as under

Private Function MyDataTable() As DataTable
Dim dtsource As New DataTable("Details")

'Adding columns to datatable
dtsource.Columns.Add("Name", GetType(String))
dtsource.Columns.Add("Gender", GetType(Boolean))

'Adding records to the datatable
dtsource.Rows.Add("Name1", 1)
dtsource.Rows.Add("Name2", 1)
dtsource.Rows.Add("Name3", 0)
dtsource.Rows.Add("Name4", 1)
dtsource.Rows.Add("Name5", 0)

Return dtsource
End Function

Then fire the below query

Dim dt = (From dr In MyDataTable().AsEnumerable()New With { _
Key .Name = dr.Field(Of String)("Name"), _
Key .Category = dr.Field(Of Boolean)("Gender"), _
Key .NewCategory = If(dr.Field(Of Boolean)("Gender"), "Male", "Female") _

We are using the AsEnumerable() extension method which is available in System.Data.DataSetExtensions assembly.

Comments or Responses

Login to post response