title: How to convert Linq result to Datatable (using datatable not context)
body: <p>How can i convert linq result to data table?</p>
  
  <pre><code>Dim query =  (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"))
           })
  </code></pre>
  
  <p>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)</p>
  
  <pre><code>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
  </code></pre>