2

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

Vivian River
  • 31,198
  • 62
  • 198
  • 313

1 Answers1

8

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");
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • +1: Thanks, Jon. So... I presume that this `AsEnumerable` method must impose some cost; otherwise the class would implement IEnumerable by default. Can you tell me what that cost is? – Vivian River Nov 15 '10 at 20:52