Simple Methods to Convert DataRow Array to DataTable

Nov 20, 2025 · Programming · 9 views · 7.8

Keywords: C# | DataRow | DataTable | Array Conversion | ImportRow | CopyToDataTable

Abstract: This article explores two primary methods for converting a DataRow array to a DataTable in C#: using the CopyToDataTable extension method and manual iteration with ImportRow. It covers scenarios, best practices, handling of empty arrays, schema matching, and includes comprehensive code examples and performance insights.

Introduction

In C# programming, data manipulation is a frequent task, especially when working with ADO.NET for database operations. DataTable and DataRow are core data structures. There are scenarios where converting an array of DataRow objects to a new DataTable is necessary, such as in data filtering, export, or transformation. Based on real-world Q&A data and reference articles, this article delves into two simple and effective methods to help developers handle such conversions efficiently.

Method 1: Using the CopyToDataTable Extension Method

In .NET Framework 3.5 and later, Microsoft introduced the CopyToDataTable extension method, which is part of the System.Data.DataSetExtensions namespace. It is designed for IEnumerable<DataRow> collections, including DataRow[] arrays. Here is a basic example:

DataTable dt = new DataTable();
DataRow[] dr = dt.Select("Your condition");
if (dr.Length > 0)
{
    DataTable dt1 = dr.CopyToDataTable();
}

The key advantage of this method is its simplicity: a single line of code can complete the conversion. However, developers must note that if the array is empty, calling CopyToDataTable throws an InvalidOperationException with the message "The source contains no DataRows." Therefore, checking the array length beforehand is a necessary precaution. According to MSDN documentation, this method is suitable for scenarios involving LINQ queries or other operations that return DataRow collections.

Method 2: Manual Iteration with ImportRow

As the best answer, the manual iteration method offers greater flexibility and compatibility. This approach involves iterating through the DataRow array and using the ImportRow method to add each row to the target DataTable. Here is the implementation code:

DataTable dataTable = new DataTable();
foreach (DataRow row in rowArray)
{
    dataTable.ImportRow(row);
}

A critical aspect of this method is ensuring that the schema (i.e., column structure) of the target DataTable matches that of the source DataRow array. If the schemas do not match, it may lead to data loss or exceptions. In practice, developers can first clone the schema from the source DataTable:

DataTable clonedTable = originalTable.Clone();
foreach (DataRow row in rowArray)
{
    clonedTable.ImportRow(row);
}

This approach avoids the "This row already belongs to another table" error because ImportRow creates a copy of the row rather than directly referencing the original. From a performance perspective, the iteration method is efficient for small arrays and is compatible with earlier .NET versions.

Method Comparison and Selection Advice

Both methods have their pros and cons: CopyToDataTable is concise but depends on specific .NET versions and extension libraries, while manual iteration is more versatile but requires more code. When choosing, consider the following factors:

Based on reference articles, in dynamic column scenarios, combining schema cloning with iteration is the most reliable method to ensure data integrity.

Practical Applications and Extensions

In real-world development, such as importing data from Excel or performing data filtering, these methods are highly practical. For example, to filter rows from a DataTable based on specific criteria and convert them to a new table:

DataTable sourceTable = GetDataFromExcel();
DataRow[] filteredRows = sourceTable.Select("ColumnName > 100");
DataTable newTable = sourceTable.Clone();
foreach (DataRow row in filteredRows)
{
    newTable.ImportRow(row);
}

This code snippet demonstrates how to combine cloning and iteration to avoid schema mismatch issues. Additionally, reference articles mention that similar methods apply in automation tools like UIPath, but attention must be paid to referencing extension libraries.

Conclusion

Converting a DataRow array to a DataTable is a common requirement in C# data handling. This article has detailed two primary methods: the CopyToDataTable extension method and manual iteration with ImportRow. The former is ideal for modern .NET environments, emphasizing code brevity; the latter offers better compatibility and control. Developers should select the appropriate method based on project needs, .NET version, and error-handling strategies. By understanding core concepts and best practices, one can efficiently address data conversion challenges, enhancing code quality and maintainability.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.