1

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?

  • Not compile means? is it throwing any exception? if yes then provide error. – Prasad Telkikar Sep 27 '19 at 13:20
  • It simple isn't valid code, if I write .Select (even after including the System.Linq namespace) it has a red line under it, it's not valid, it won't build. –  Sep 27 '19 at 13:21
  • No, System.Linq has been added. –  Sep 27 '19 at 13:21
  • Not sure why I received a downvote for this - I don't mind downvotes if they're explained with constructive criticism but can't see what's wrong here!? –  Sep 27 '19 at 13:22
  • 3
    `myDataRowCollection.Cast().ToList()` ... extensions are for `IEnumerable` not `IEnumerable` – Selvin Sep 27 '19 at 13:25
  • related https://stackoverflow.com/questions/4974159/convert-datarowcollection-to-ienumerablet – xdtTransform Sep 27 '19 at 13:29

1 Answers1

5

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.

H H
  • 263,252
  • 30
  • 330
  • 514
  • Ah OK, thanks Henk. My question is less about why foreach works and more about why the linq extensions don't though, given the fact the foreach does. This type does implement `IEnumerable` –  Sep 27 '19 at 13:25
  • @xdtTransform it also implements IEnumerable. It implements both. –  Sep 27 '19 at 13:28
  • https://learn.microsoft.com/en-us/dotnet/api/system.data.internaldatacollectionbase?view=netframework-4.8 –  Sep 27 '19 at 13:28
  • Thanks for the update Henk, that explains it. Much appreciated, will mark as answer when I can. –  Sep 27 '19 at 13:29
  • deleted my comment to make a more clear one but Henk edited his answer faster. For Work around please refer to https://stackoverflow.com/questions/4974159/convert-datarowcollection-to-ienumerablet . – xdtTransform Sep 27 '19 at 13:32
  • Henk also added details of a workaround haha Thank you @xdtTransform - appreciate the help –  Sep 27 '19 at 13:33
  • I prefer the "Why" and the "How to work around" to be different to prevent ppl from closing Why question as duplicate of work around. – xdtTransform Sep 27 '19 at 13:34