LINQ query on a DataTable object

I’m trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:

var results = from myRow in myDataTable where
results.Field(“RowNo”) == 1 select results;

I’m amazed that LINQ queries are not allowed on DataTables!

You can’t query against the DataTable’s Rows collection, since DataRowCollection doesn’t implement IEnumerable. You need to use the AsEnumerable() extension for DataTable. Like so:

			var results = from myRow in myDataTable.AsEnumerable() 
			where myRow.Field("RowNo") == 1 
			select myRow; 


you'll need to add a reference to System.Data.DataSetExtensions

AsEnumerable() returns IEnumerable. If you need to convert IEnumerable to a DataTable, use the CopyToDataTable() extension.