Search This Blog

Tuesday, January 29, 2013

Filter DataTable with LINQ (Visual Basic)


VB.NET > Data > DataTable > Filter with LINQ

Use AsEnumerable method to return the input type DataTable as IEnumerable.
The CopyToDataTable method takes the results of a query and copies the data into a DataTable.






Example:

Public Class Form1

  Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim dt As DataTable = New DataTable("table")
    dt.Columns.Add("id", Type.GetType("System.Int32"))
    dt.Columns.Add("name", Type.GetType("System.String"))

    Dim dr As DataRow = dt.NewRow()
    dr("id") = 1
    dr("name") = "john"
    dt.Rows.Add(dr)

    dr = dt.NewRow()
    dr("id") = 2
    dr("name") = "dan"
    dt.Rows.Add(dr)

    Dim filteredTable As DataTable = (From n In dt.AsEnumerable()
        Where n.Field(Of Int32)("id") = 1
                    Select n).CopyToDataTable()

    ComboBox1.DataSource = filteredTable
    ComboBox1.DisplayMember = "name"
    ComboBox1.ValueMember = "id"
  End Sub

End Class