I like the syntax offered by the .Where()
method that is available for many collections. However, I've noticed that it is conspicuously absent from some collections.
I'm sure that this has to do with some interface being implemented or not implemented, but beyond that, I would like to know why we don't have a .Where()
method on DataTable.Rows
DataRowCollection
only implements IEnumerable
, not IEnumerable<DataRow>
.
An extension method exists - DataTableExtensions.AsEnumerable
- to effectively "fix" this. You could also just call table.Cast<DataRow>()
but the EnumerableRowCollection
returned by AsEnumerable
has a bit more functionality on it.
So you can write:
var query = from row in table.AsEnumerable()
where ...
select ...;
There are other useful extension methods in DataRowExtensions
, most notably Field
, so you can write:
var query = from row in table.AsEnumerable()
where row.Field<int>("Age") > 18
select row.Field<string>("Name");