Convert DataRowCollection to IEnumerable<T>

泪湿孤枕 提交于 2019-12-17 16:00:12

问题


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

回答1:


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



回答2:


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




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/4974159/convert-datarowcollection-to-ienumerablet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!