Search code examples
c#linqforeachdatarowcollection

Why can I not iterate over something with linq that can be iterated over with foreach?


I have a collection of table rows (type DataRowCollection). It is perfectly valid for me to write:

foreach(var row in myDataRowCollection)
{
  // Something with row
}

Yet the following will not compile:

myDataRowCollection.ToList();

or even

myDataRowCollection.Select(...

What are these System.Linq extensions expecting that DataRowCollection doesn't implement?


Solution

  • foreach() is pattern based (docs), it does not actually rely on IEnumerable. GetEnumerator() is enough.

    class A // note: no interface
    {
        public IEnumerator GetEnumerator() { ...} 
    }
    

    Linq on the other hand is based on extension methods for IEnumerable<T>.

    Your DataRowCollection implements IEnumerable but not IEnumerable<DataRow>. It is too old for Linq.

    But there are some helper methods available, myDataRowCollection.AsEnumerable().Select(...) should work.