C# – How to convert a DataTable into a generic list


Currently, I'm using:

DataTable dt = CreateDataTableInSomeWay();

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

Is there a better/magic way?

Best Solution

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();


using System.Linq;
List<DataRow> list = dt.AsEnumerable().ToList();