Transforming DataTables into Generic Lists in C#
Several methods exist for converting a DataTable to a generic list in C#. A common approach involves iterating through each row and adding it to the list.
<code class="language-C#">DataTable dt = CreateDataTableInSomeWay(); List<DataRow> list = new List<DataRow>(); foreach (DataRow dr in dt.Rows) { list.Add(dr); }</code>
A More Efficient Method: Extension Methods
.NET 3.5 and later versions offer a more efficient solution using extension methods from the DataTableExtensions
class. The AsEnumerable()
method transforms the DataTable into an IEnumerable<DataRow>
, which can then be easily converted to a List<DataRow>
using ToList()
.
<code class="language-C#">IEnumerable<DataRow> sequence = dt.AsEnumerable(); // Or, more directly: using System.Linq; ... List<DataRow> list = dt.AsEnumerable().ToList();</code>
This LINQ-based approach avoids explicit looping, resulting in cleaner and potentially faster code.
Performance Analysis
When choosing a conversion method, performance is key. Row-by-row iteration can be slow with large DataTables. The AsEnumerable()
and ToList()
method combination generally offers superior performance due to its optimized implementation.
The above is the detailed content of How Can I Efficiently Convert a DataTable to a Generic List in C#?. For more information, please follow other related articles on the PHP Chinese website!