Hi,
I want to convert LINQ query result to datatable in vb.net 4.0.
Please advise how to do it?
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Santhosh Kumar JayaramanPosted Jun 18, 2012, 1:47 AM
http://www.c-sharpcorner.com/UploadFile/1a81c5/list-to-datatable-converter-using-C-Sharp/
Santhosh Kumar JayaramanPosted Jun 18, 2012, 1:12 AM
Get the linq query result as List. Then call this function.
Public Function ToDataTable(ByVal items As List(Of T)) As DataTable
Dim dataTable As DataTable = New DataTable(GetType(T).Name)
'Get all the properties
Dim Props() As PropertyInfo = GetType(T).GetProperties((BindingFlags.Public Or BindingFlags.Instance))
For Each prop As PropertyInfo In Props
'Setting column names as Property names
dataTable.Columns.Add(prop.Name)
Next
For Each item As T In items
Dim values As var = New Object((Props.Length) - 1) {}
Dim i As Integer = 0
Do While (i < Props.Length)
'inserting property values to datatable rows
values(i) = Props(i).GetValue(item, Nothing)
i = (i + 1)
Loop
dataTable.Rows.Add(values)
Next
'put a breakpoint here and check datatable
Return dataTable
End Function