77

I would like to do something like this in .NET 3.5. What's the quickest way?

IEnumerable<DataRow> collection = 
    TypedDataSet.TypedTableBase<DataRow>.Rows as IEnumerable<DataRow>;
FMFF
  • 1,652
  • 4
  • 32
  • 62
Abdu
  • 16,129
  • 13
  • 59
  • 84

4 Answers4

100

You can call OfType<DataRow>() on the DataRowCollection.

wsanville
  • 37,158
  • 8
  • 76
  • 101
  • 7
    This is the simplest solution – Luiz Eduardo May 29 '15 at 20:48
  • 2
    This is really no different than calling Cast() on the DataRowCollection, which is already in the accepted answer. (except if we're splitting hairs, I believe OfType does some unnecessary filtering that Cast doesn't bother with) – Kevin Holt Mar 29 '17 at 22:14
  • 1
    @KevinHolt no I would say they are the same if and only if you know for certain the only type of objects in the collection are castable to DataRows... in the case of a DataRowCollection, that's true, but in most non-generic `IEnumerable`s it definitely isn't. – Jeremy Holovacs Aug 09 '19 at 17:41
  • Right I'm not saying that IEnumerable.OfType() and IEnumerable.Cast() always do the same thing for any T and R, and I wasn't trying to imply that. However, I am saying (and it sounds like you agree with me) that they do the same thing in the case where R=T, such as the OP's actual question which I read as asking specifically about T=R=DataRow. – Kevin Holt Aug 12 '19 at 17:51
85

Assuming you're using .NET 4.0, which introduces covariance:

// Presumably your table is of some type deriving from TypedTableBase<T>,
// where T is an auto-generated type deriving from DataRow.
IEnumerable<DataRow> collection = myTypedTable;

The table type itself implements IEnumerable<T> where T : DataRow.

Otherwise:

IEnumerable<DataRow> collection = myTypedTable.Cast<DataRow>();
Dan Tao
  • 125,917
  • 54
  • 300
  • 447
  • 1
    This and wsanville's answers were relevant for me. It happens that Cast throws an exception when it finds an item which cannot be cast to TResult. On the other hand, OfType only returns items which are of type TResult. See the documentation on https://msdn.microsoft.com/en-us/library/bb360913(v=vs.110).aspx – Th3B0Y Dec 21 '16 at 09:24
5

A simple direct solution is to use the method "Select()" of a System.Data.DataTable object, which produces DataRow[]. From this you can treat as an IEnumerable<DataRow> using Linq like below:

List<MyItem> items = dtItems.Select()
                            .Select(row => new MyItem(row))
                            .ToList();

Providing a useful list of objects for each row.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Michael Erickson
  • 4,217
  • 2
  • 23
  • 10
1

There is a built in extension method if you include System.Data.DataSetExtensions.dll in to your project that adds a AsEnumerable() method.

IEnumerable<DataRow> collection = TypedDataSet.TypedTableBase<DataRow>.AsEnumerable();
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431