Convert DataRowCollection to IEnumerable <T>

I would like to do something similar in .NET 3.5. What is the fastest way?

IEnumerable<DataRow> collection = TypedDataSet.TypedTableBase<DataRow>.Rows as IEnumerable<DataRow>; 
+45
c # linq ienumerable
Feb 11 2018-11-21 at
source share
4 answers

Assuming you are 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>(); 
+48
Feb 11 2018-11-21 at
source share

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

+64
Feb 11 2018-11-21 at
source share

A simple direct solution is to use the "Select ()" method of the System.Data.DataTable object that creates the "DataRow []". From this, you can treat it as IEnumberable using Linq, as shown below:

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

Providing a useful list of objects for each row.

+1
Jan 09 '17 at 1:42 on
source share

There is a built-in extension method if you add System.Data.DataSetExtensions.dll to your project, which adds the AsEnumerable() method.

 IEnumerable<DataRow> collection = TypedDataSet.TypedTableBase<DataRow>.AsEnumerable(); 
0
Oct 10 '17 at 21:14
source share



All Articles