Home > Backend Development > C++ > How Can I Efficiently Convert a DataTable to a Generic List in C#?

How Can I Efficiently Convert a DataTable to a Generic List in C#?

Mary-Kate Olsen
Release: 2025-01-18 16:56:14
Original
292 people have browsed it

How Can I Efficiently Convert a DataTable to a Generic List in C#?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template