What's the best performing way to convert a DataRowCollection instance to a DataRow[]?
Asked
Active
Viewed 5.1k times
4 Answers
18
For the sake of completeness, this is another way (with Linq), and it preserve the row ordering:
DataRow[] rows = dt.Rows.Cast<DataRow>().ToArray()

Nordin
- 3,087
- 5
- 28
- 35
5
This is kind of obvious, but:
DataRowCollection.CopyTo(DataRow[] array, Int32 offset)
?
It seems like no matter what, you're going to have to iterate the collection (CopyTo iterates the internal DataRowTree elements).
I suppose you could use reflection to access the non-public tree, but at a significant cost.
5
If you have not access to the containing table, you may use the extension method:
public static class DataRowCollectionExtensions
{
public static IEnumerable<DataRow> AsEnumerable(this DataRowCollection source)
{
return source.Cast<DataRow>();
}
}
And thereafter:
DataRow[] dataRows = dataRowCollection.AsEnumerable().ToArray();
But if you have access to the containing table, it's better to access rows using DataTable
's AsEnumerable
extension method (Description, Source):
DataRow[] dataRows = dataTable.AsEnumerable().ToArray();
Either way you may use DataTable
's Select
method with several overloads (Description, Source):
DataRow[] dataRows = dataTable.Select();

Deilan
- 4,740
- 3
- 39
- 52