C# 将 DataRowCollection 转换为 DataRow[]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/227215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:59:27  来源:igfitidea点击:

Convert DataRowCollection to DataRow[]

c#performancedatarowdatarowcollection

提问by

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

将 DataRowCollection 实例转换为 DataRow[] 的最佳执行方式是什么?

回答by Jared

This is kind of obvious, but:

这很明显,但是:

DataRowCollection.CopyTo(DataRow[] array, Int32 offset)?

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).

似乎无论如何,您都必须迭代集合(CopyTo 迭代内部 DataRowTree 元素)。

I suppose you could use reflection to access the non-public tree, but at a significant cost.

我想您可以使用反射来访问非公共树,但成本很高。

回答by Ely

DataRow[] rows = dt.Select();

Assuming you still have access to the datatable.

假设您仍然可以访问数据表。

回答by Nordin

For the sake of completeness, this is another way (with Linq), and it preserve the row ordering:

为了完整起见,这是另一种方式(使用 Linq),它保留了行顺序

DataRow[] rows = dt.Rows.Cast<DataRow>().ToArray()

回答by Deilan

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 AsEnumerableextension method (Description, Source):

但是,如果您有权访问包含表,最好使用DataTableAsEnumerable扩展方法(DescriptionSource)访问行:

DataRow[] dataRows = dataTable.AsEnumerable().ToArray();

Either way you may use DataTable's Selectmethod with several overloads (Description, Source):

无论哪种方式,您都可以将DataTableSelect方法与多个重载(DescriptionSource)一起使用:

DataRow[] dataRows = dataTable.Select();