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.
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]
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()