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;
This is not allowed. How do I get something like this working?
I'm amazed that LINQ queries are not allowed on DataTables!
Best Answer
You can't query against the
DataTable
's Rows collection, sinceDataRowCollection
doesn't implementIEnumerable<T>
. You need to use theAsEnumerable()
extension forDataTable
. Like so:And as @Keith says, you'll need to add a reference to System.Data.DataSetExtensions
AsEnumerable()
returnsIEnumerable<DataRow>
. If you need to convertIEnumerable<DataRow>
to aDataTable
, use theCopyToDataTable()
extension.Below is query with Lambda Expression,