52

What's the best performing way to convert a DataRowCollection instance to a DataRow[]?

4 Answers4

108
DataRow[] rows = dt.Select();

Assuming you still have access to the datatable.

Seibar
  • 68,705
  • 38
  • 88
  • 99
Ely
  • 3,200
  • 1
  • 21
  • 18
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.

Seibar
  • 68,705
  • 38
  • 88
  • 99
Jared
  • 2,007
  • 15
  • 14
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