Convert DataRowCollection to IEnumerable<T>

C#.NetLinq.Net 3.5Ienumerable

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - C#

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 IEnumberable using Linq like below:

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

Providing a useful list of objects for each row.

Solution 4 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbduView Question on Stackoverflow
Solution 1 - C#wsanvilleView Answer on Stackoverflow
Solution 2 - C#Dan TaoView Answer on Stackoverflow
Solution 3 - C#Michael EricksonView Answer on Stackoverflow
Solution 4 - C#Scott ChamberlainView Answer on Stackoverflow