5

I found that it is not possible to directly use LINQ over an instance of IEnumerable<T> i.e. System.Data.DataRowCollection

This class derives from the class System.Data.InternalDataCollectionBase which implements IEnumerable<T>, so it makes completely sense to being able to use LINQ functions over System.Data.DataRowCollection.... but I can't.

Check the following example:

using (DBConnection connExport = DBConnection.OpenConnection())
{
    DataTable dt = GetDataTableFromDatabase();

    DataRow dr1 = dt.Rows.First(); // This LINQ is not allowed
    foreach(DataRow dr in dt.Rows) // But enumerating it works fine
    {
            // Some processing...
    }
}

I have searched on the official docs of LINQ where I found

The standard query operators allow queries to be applied to any Enumerable-based information source.

I know that the reason should be something very simple, but I cannot figure out what is it. So here I go:

Why is LINQ for instances of System.Data.DataRowCollection not allowed?

[EDIT]: There is already an answer for HOW to overcome this, but not to the WHY, so that's my purpose with this: to understand, not to overcome.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
monsieurgutix
  • 137
  • 1
  • 7
  • Not the answer but _dt.AsEnumerable().FirstOrDefault()_ will allow you to use LINQ on a DataTable – Steve Oct 10 '17 at 20:25
  • 4
    It's not `IEnumerable`. It's just `System.Collections.IEnumerable`. – 15ee8f99-57ff-4f92-890c-b56153 Oct 10 '17 at 20:27
  • Based on your edit you are also looking for *Why cannot use LINQ* Check the @EdPlunkett comment to know why you can't use LINQ. Simply because it is not `IEnumerable` that I have already mentioned in my answer too. – Salah Akbari Oct 10 '17 at 20:56
  • @monsieurgutix I tried but couldn't submit, since the question was already closed. Fifteen Pokémon points more or less is of no great consequence to me anyhow. The important thing is you got your answer. – 15ee8f99-57ff-4f92-890c-b56153 Oct 10 '17 at 21:39
  • I would love that @dasblinkerlight would share your thoughts on users finding an answer, not just closing any question and not coming back to realise that I was really asking for something diffrerent he thought of. – monsieurgutix Oct 11 '17 at 14:31

1 Answers1

6

It's of type System.Collections.IEnumerable not IEnumerable<T> but you can use Cast or OfType to use LINQ here:

DataRow dr1 = dt.Rows.Cast<DataRow>().First(); 
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109