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!
Linq can help to perform complex queries on a datatable easily. We can use the different querying capabilities of the linq for performing different operations. For example we can project only few specific columns from a datatable using the select operation.
Data sources that implement the IEnumerable<T> generic interface can be queried through LINQ. Calling AsEnumerable on a DataTable returns an object which implements the generic IEnumerable<T> interface, which serves as the data source for LINQ to DataSet queries.
You can use query expression syntax or method-based query syntax to perform queries against single tables in a DataSet, against multiple tables in a DataSet, or against tables in a typed DataSet.
Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.
You can't query against the DataTable
's Rows collection, since DataRowCollection
doesn't implement IEnumerable<T>
. You need to use the AsEnumerable()
extension for DataTable
. Like so:
var results = from myRow in myDataTable.AsEnumerable() where myRow.Field<int>("RowNo") == 1 select myRow;
And as @Keith says, you'll need to add a reference to System.Data.DataSetExtensions
AsEnumerable()
returns IEnumerable<DataRow>
. If you need to convert IEnumerable<DataRow>
to a DataTable
, use the CopyToDataTable()
extension.
Below is query with Lambda Expression,
var result = myDataTable .AsEnumerable() .Where(myRow => myRow.Field<int>("RowNo") == 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With