Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DataTable to List<T>

I have an strongly typed DataTable of type MyType, I'd like convert it in a List<MyType>.

How can I do this ?

Thanks.

like image 857
Kris-I Avatar asked Sep 15 '09 14:09

Kris-I


People also ask

What is a DataTable in C#?

In the ADO.NET library, C# DataTable is a central object. It represents the database tables that provide a collection of rows and columns in grid form. There are different ways to create rows and columns in the DataTable.


2 Answers

The following does it in a single line:

dataTable.Rows.OfType<DataRow>()     .Select(dr => dr.Field<MyType>(columnName)).ToList(); 

[Edit: Add a reference to System.Data.DataSetExtensions to your project if this does not compile]

like image 153
Yuriy Faktorovich Avatar answered Oct 05 '22 14:10

Yuriy Faktorovich


List<MyType> listName = dataTableName.AsEnumerable().Select(m => new MyType() {    ID = m.Field<string>("ID"),    Description = m.Field<string>("Description"),    Balance = m.Field<double>("Balance"), }).ToList() 
like image 28
Richard YS Avatar answered Oct 05 '22 13:10

Richard YS