Abdu
Abdu

Reputation: 16585

Convert DataRowCollection to IEnumerable<T>

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>;

Upvotes: 80

Views: 67517

Answers (4)

Michael Erickson
Michael Erickson

Reputation: 4445

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.

Upvotes: 5

Scott Chamberlain
Scott Chamberlain

Reputation: 127573

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();

Upvotes: 1

Dan Tao
Dan Tao

Reputation: 128317

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>();

Upvotes: 86

wsanville
wsanville

Reputation: 37516

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

Upvotes: 104

Related Questions