I have an strongly typed DataTable of type MyType
, I\'d like convert it in a List
.
How can I do this ?
Thanks.
please try this code:
public List<T> ConvertToList<T>(DataTable dt)
{
var columnNames = dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName)
.ToList();
var properties = typeof(T).GetProperties();
return dt.AsEnumerable().Select(row =>
{
var objT = Activator.CreateInstance<T>();
foreach (var pro in properties)
{
if (columnNames.Contains(pro.Name))
pro.SetValue(objT, row[pro.Name]);
}
return objT;
}).ToList();
}
Create a list with type<DataRow>
by extend the datatable
with AsEnumerable
call.
var mylist = dt.AsEnumerable().ToList();
Cheers!! Happy Coding