C# 如何将数据行转换为对象数组?

C# 如何将数据行转换为对象数组?,c#,arrays,datarow,C#,Arrays,Datarow,我有一个数据行,我想把它做成一个对象数组,因为要把它添加到我的数据表中,我需要一个对象数组。到目前为止,我所做的是 data_table.Rows.Add(data_row.ToArray<object>()); 但这不起作用,因为它不提供对象数组,至少我的编译器告诉我这一点您可以像这样对DataRow进行扩展方法: public static class DataRowExtension { // Class for: Conversion to object[]

我有一个数据行,我想把它做成一个对象数组,因为要把它添加到我的数据表中,我需要一个对象数组。到目前为止,我所做的是

data_table.Rows.Add(data_row.ToArray<object>());

但这不起作用,因为它不提供对象数组,至少我的编译器告诉我这一点

您可以像这样对DataRow进行扩展方法:

public static class DataRowExtension 
{
    // Class for: Conversion to object[]
    public static object[] ToObjectArray(this DataRow dataRow)
    {
        // Identifiers used are:
        int columnCount = dataRow.Table.Columns.Count;
        object[] objectArray = new object[columnCount];

        // Check the row is not empty
        if (columnCount == 0)
        {
            return null;
        }

        // Go through the row to add each element to the array
        for (int i = 0; i < columnCount; i++)
        {
            objectArray[i] = dataRow[i];
        }

        // Return the object array
        return objectArray;
    }
}
扩展方法很棒。

您可以对数据行类型使用ItemArray属性


这么快又简单,不需要在前面加上$或@,或者object[]正在为那行代码处理这些吗?谢谢,但这对我来说太复杂了
object[] arr = data_row.ItemArray;