score:3

Accepted answer

Generally LINQ queries works on data sources which implement the IEnumerable<T>/ IQueryable<T> Interface. But DataTable does not implement any of these. So we can not directly apply LINQ queries on a DataTable.

But DataTable class has an extension method called AsEnumerable which returns an IEnumerable collection of DataRow. So we can apply the AsEnumerable function on a DataTable and then play with some LINQ on the resulting collection.

var items=(from p in myDataTable.AsEnumerable()
                 select new { ID= p.Field<int>("ID").
                              Name=p.Field<string>("Name")
                           }).ToList();
var filtered=items.Where(x => x.Name.Contains("Mike"));

EDIT : Here is the VB.NET Version ( Disclaimer: I am not a VB.NET guy. but i could build this code without any error)

Dim items = (From p In myDataTable.AsEnumerable() 
               Select New With {.ID = p.Field(Of Integer)("ID"),
                                .Name = p.Field(Of String)("Name")}).ToList()

Dim filtered = items.Where(Function(x) x.Name.Contains("Mike")).ToList()

score:0

VB

Private Function likes(ByVal dt As DataTable, ByVal column As String, ByVal value As String)
    Dim result = dt.Clone()
    For Each row As DataRow In From row1 As DataRow In dt.Rows Where (row1(column).Contains(value))
        result.ImportRow(row)
    Next
    Return result
End Function

C#

private DataTable likes(ref DataTable dt, string column, string value)
 {
    DataTable result = dt.Clone();
    foreach (DataRow row in from row1 in dt.Rowswhere (row1(column).Contains(value))) {
        result.ImportRow(row);
    }
    return result;
 }

Related Articles