How to convert Linq result to Datatable (using datatable not context)

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How to convert Linq result to Datatable (using datatable not context)



How can i convert linq result to data table?


Dim result = (From e In dsCart.Tables(0).AsEnumerable()
Group e By
DistNum = e("DistNum"),
DistributorName = e("DistributorName"),
SourceID = e("SourceID")
Into Group
Select New With
.DistNum = DistNum,
.DistributorName = DistributorName,
.TotalOrderAmt = Group.Sum(Function(x) x.Field(Of Decimal)("ExtendedAmt")),
.ItemQty = Group.Count(Function(x) x.Field(Of Integer)("ItemQty"))
)



I have come across the following method to convert linq var to data table but i am getting error 'The type arguments for method cannot be inferred from the usage' when calling gv.DataSource = ToDataTable(query)


private Function ToDataTable(Of T)(collection As IEnumerable(Of T)) As DataTable
Dim dt As New DataTable()
Dim _t As Type = GetType(T)
Dim pia As PropertyInfo() = _t.GetProperties()

'Create the columns in the DataTable
For Each pi As PropertyInfo In pia
dt.Columns.Add(pi.Name, If(Nullable.GetUnderlyingType(pi.PropertyType), pi.PropertyType))
Next

'Populate the table
For Each item As T In collection
Dim dr As DataRow = dt.NewRow()
dr.BeginEdit()
For Each pi As PropertyInfo In pia
dr(pi.Name) = pi.GetValue(item, Nothing)
Next
dr.EndEdit()
dt.Rows.Add(dr)
Next

Return dt
End Function





There is no ToDataTable method or the like so you do exactly what people have been doing since the beginning of .NET to populate a DataTable with data from a list of objects.
– jmcilhinney
8 mins ago


ToDataTable


DataTable





Of course, you could write your own ToDataTable method and then call that here and in similar situations in the future.
– jmcilhinney
8 mins ago


ToDataTable









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard