将DataRowCollection转换为DataRow[]
本文关键字:DataRow DataRowCollection 转换 | 更新日期: 2023-09-27 17:48:52
将DataRowCollection实例转换为DataRow[]的最佳方式是什么?
DataRow[] rows = dt.Select();
假设您仍然可以访问数据表。
为了完整性,这是另一种方式(使用Linq),并且它保留行排序:
DataRow[] rows = dt.Rows.Cast<DataRow>().ToArray()
这有点明显,但:
DataRowCollection.CopyTo(DataRow[] array, Int32 offset)
?
不管怎样,似乎都必须迭代集合(CopyTo迭代内部DataRowTree元素)。
我想您可以使用反射来访问非公共树,但要付出巨大的代价。
如果您没有访问包含表的权限,您可以使用扩展方法:
public static class DataRowCollectionExtensions
{
public static IEnumerable<DataRow> AsEnumerable(this DataRowCollection source)
{
return source.Cast<DataRow>();
}
}
此后:
DataRow[] dataRows = dataRowCollection.AsEnumerable().ToArray();
但是,如果您有权访问包含表,最好使用DataTable
的AsEnumerable
扩展方法(Description,Source):来访问行
DataRow[] dataRows = dataTable.AsEnumerable().ToArray();
无论哪种方式,您都可以使用带有多个重载的DataTable
的Select
方法(描述,来源):
DataRow[] dataRows = dataTable.Select();