Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ query on a DataTable

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!

like image 532
Calanus Avatar asked Aug 14 '08 10:08

Calanus


People also ask

Can I use LINQ on DataTable?

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.

How can you load data into DataSet so that it can be queried using LINQ?

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.

How can LINQ queries be performed against multiple tables in a DataSet?

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.

What are LINQ queries in C#?

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.


1 Answers

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); 
like image 67
Collin K Avatar answered Sep 30 '22 02:09

Collin K