将DataRowCollection转换为IEnumerable <t> </t>

时间:2011-02-11 21:18:03

标签: c# .net linq .net-3.5 ienumerable

我想在.NET 3.5中做这样的事情。什么是最快的方式?

IEnumerable<DataRow> collection = 
    TypedDataSet.TypedTableBase<DataRow>.Rows as IEnumerable<DataRow>;

4 个答案:

答案 0 :(得分:78)

您可以在OfType<DataRow>()上致电DataRowCollection

答案 1 :(得分:63)

假设您使用的是.NET 4.0,它引入了协方差:

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

table type itself实施IEnumerable<T> where T : DataRow

否则:

IEnumerable<DataRow> collection = myTypedTable.Cast<DataRow>();

答案 2 :(得分:3)

一个简单的直接解决方案是使用System.Data.DataTable对象的方法“Select()”,它生成“DataRow []”。从这里你可以使用Linq作为IEnumberable,如下所示:

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

为每一行提供有用的对象列表。

答案 3 :(得分:0)

如果您在项目中添加System.Data.DataSetExtensions.dll并添加AsEnumerable()方法,则会有内置的扩展方法。

IEnumerable<DataRow> collection = TypedDataSet.TypedTableBase<DataRow>.AsEnumerable();
相关问题