How do you convert a DataTable into a generic list?


Question

Currently, I'm using:

DataTable dt = CreateDataTableInSomeWay();

List<DataRow> list = new List<DataRow>(); 
foreach (DataRow dr in dt.Rows)
{
    list.Add(dr);
}

Is there a better/magic way?

2
168
10/16/2008 1:23:50 PM

Accepted Answer

If you're using .NET 3.5, you can use DataTableExtensions.AsEnumerable (an extension method) and then if you really need a List<DataRow> instead of just IEnumerable<DataRow> you can call Enumerable.ToList:

IEnumerable<DataRow> sequence = dt.AsEnumerable();

or

using System.Linq;
...
List<DataRow> list = dt.AsEnumerable().ToList();
256
1/11/2016 2:42:32 PM

Exper Answer

With C# 3.0 and System.Data.DataSetExtensions.dll,

List<DataRow> rows = table.Rows.Cast<DataRow>().ToList();
34
10/16/2008 1:28:03 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon