Tuesday, 5 February 2013

LINQ query to DataTable

Converting Anonymous type generated by LINQ to a DataTable type(here LINQ left outer join)

  customer                                                      city

id   name  city_id                                     cid       city_name                         

1     xxx        2                                             1           aaa

2     yyy         3                                            2           bbb

                                                                     3           ccc

First create temporary datatable with columns you need

Dim tbTemp As New DataTable

Using left outer join  

 Dim JoinedResult As IEnumerable(Of DataRow) = From t1 In                                                customer.AsEnumerable()
         Group Join t2 In city.AsEnumerable()
         On t1.Field(Of String)("city_id") Equals t2.Field(Of String)("cid")
        Into RightTableResults = Group
        From t In RightTableResults.DefaultIfEmpty
        Select tbTemp.LoadDataRow(New Object() {t1.Item("cust_name"),      t.Item("city_name")})

 Dim tbResult As New DataTable





No comments:

Post a Comment