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
Abdu Feb 11 2018-11-21 at 18:18
source share4 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
Dan Tao Feb 11 2018-11-21 at 21:20
source shareYou can call OfType<DataRow>() on the DataRowCollection .
+64
wsanville Feb 11 2018-11-21 at 21:20
source shareA 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
Michael Erickson Jan 09 '17 at 1:42 on 2017-01-09 01:42
source shareThere 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
Scott Chamberlain Oct 10 '17 at 21:14 2017-10-10 21:14
source share