Jarloo

Menu

LINQ to DataTable

LINQ is probably one of the best features in .NET. I find myself using it constantly, but was a stuck when I attempted to use LINQ with a DataTable, as it just wouldn’t work.
After going through the trouble I figured it was worth a post about.
LINQ is probably one of the best features in .NET. I find myself using it constantly, but was a stuck when I attempted to use LINQ with a DataTable, as it just wouldn’t work. After going through the trouble I figured it was worth a post about.

Basically what was needed was a reference to System.Data.DataSetExtensions. After adding that reference you can use the AsEnumerable extension on the DataSet to get an Enumerable out of it

[box type=”info”]You will need to add a reference to System.Data.DataSetExtensions for this to work.[/box]

SqlConnection con = new SqlConnection("blah...");
con.Open();
SqlCommand cmd = new SqlCommand("select * from Customers",con);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataTable dataTable = new DataTable();
ad.Fill(dataTable);

var data = from r in dataTable.AsEnumerable()
            where r.Field<string>("LastName") == "Brown"
            select r;

You can access each field as Field(“name”).

Categories:   Code

Comments