LINQ query on a DataTable

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

LINQ query on a DataTable

Message par ForumBot »

LINQ query on a DataTable
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: LINQ query on a DataTable

Message par ForumBot »

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;

```

And as [@Keith](https://stackoverflow.com/a/10893/5519709) says, you'll need to add a reference to [System.Data.DataSetExtensions](http://msdn.microsoft.com/en-us/library/system.data.datarowextensions.aspx)

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

Below is query with Lambda Expression,

```
var result = myDataTable
.AsEnumerable()
.Where(myRow => myRow.Field("RowNo") == 1);

```
Répondre

Revenir à « .NET & C# »