Convert DataTable to IEnumerable<T> in ASP.NET Core 2.0
Here is a generic AsEnumerable extension function to mimic what the classic AsEnumerable() did, return an Enumerable collection of DataRows from a DataTable. Can be useful for someone that wishes to mimimize the amount of refactoring needed when porting their code to .net core.
public static IEnumerable<DataRow> AsEnumerable(this DataTable table)
{
for (int i = 0; i < table.Rows.Count; i++)
{
yield return table.Rows[i];
}
}
Not about most efficient but for an alternative, you can use the Select
method:
DataRow[] rows= dataTable.Select();
And now you have an IEnumerable of rows. This method may help someone:
public static List<T> ConvertDataTableToGenericList<T>(DataTable dt)
{
var columnNames = dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName)
.ToList();
var properties = typeof(T).GetProperties();
DataRow[] rows= dt.Select();
return rows.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();
}
The correct nuget package for .net core 2 is System.Data.DataSetExtensions