Tuesday, December 15, 2009

Filter & Sort DataTable using LINQ

You need to add reference to System.Data.DataSetExtensions to be able to use AsEnumerable() on a datatable.


Dim dt As New DataTable


dt.Load(myDataReader)


'get name of distinct root taxonomies


Dim root_names As IEnumerable(Of String) = From myRow In dt.AsEnumerable() _


Select myRow.Field(Of String)("root_name") Distinct


'get a list of the root taxonomy objects based on the name


Dim list As New List(Of Taxon.Taxon)


For Each root_name As String In root_names


Dim t As Taxon.Taxon = Taxon.TaxonDAL.Instance.GetOnName(root_name)


If t IsNot Nothing Then


list.Add(t)


End If


Next


'sort the root taxons by Product_DisplayOrder


list.Sort(Function(p1, p2) p1.Product_DisplayOrder.CompareTo(p2.Product_DisplayOrder))


For Each t As Taxon.Taxon In list


Dim currentRootName As String = t.name


'get the children of the current root taxon


Dim drRows As IEnumerable(Of DataRow) = From myRow In dt.AsEnumerable() _


Where myRow.Field(Of String)("root_name") = currentRootName _


Order By myRow.Field(Of Double)("Product_DisplayOrder") Ascending _


Select myRow


For Each rv As DataRow In drRows


Dim ThisTaxonId As String = rv("taxon_id")


Next


Next


Reference:

LINQ query on a DataTable

blog comments powered by Disqus