What is the fastest way to convert from DataTable to Generic List?
I have a base class that has an API that returns a DataTable based on identifiers, And I need to have an object for each identifier.
I hate to work with datatables, so I wanted to write a mapping code, that I only have to map the properties to the specific fields in the datatable.
Is there any faster way to do it rather than my exmaple?
Thanks.
pu开发者_运维百科blic abstract class BaseClass<T> where T : BaseClass<T>
{
protected abstract T MapObject(DataRow row);
protected abstract int SomeIdentifier { get; }
public IList<T> GetData()
{
return ConvertDataTableToGenericList(GetDataTableFromOtherSource(this.SomeIdentifier));
}
private IList<T> ConvertDataTableToGenericList(DataTable table)
{
IList<T> objectList = new List<T>();
foreach (DataRow row in table.Rows)
{
objectList.Add(MapObject(row));
}
return objectList;
}
}
public class DerivedClass : BaseClass<DerivedClass>
{
public int ID { get; set; }
protected override int SomeIdentifier
{
get { return 1; }
}
protected override DerivedClass MapObject(DataRow row)
{
return new DerivedClass()
{
ID = (int)row["ID"]
};
}
}
You could change your interface to work with IEnumerable<T>
and yield return
the results. The overall performance wouldn't increase but you could start faster to process the result.
As a sample:
private IEnumerable<T> ConvertDataTableToGenericList(DataTable table)
{
foreach (DataRow row in table.Rows)
{
yield return MapObject(row);
}
}
This does what you want, maybe not as readable? But very concise. I'm not a LINQ expert, so maybe this can be cleaned up. Also, not sure why you'd want to do this though...
//using System.Dynamic; <-- put this at the top
Linq<dynamic> list = (from r in table.AsEnumerable()
let eo = new ExpandoObject()
let blah = (dt.Columns.Cast<DataColumn>().All(dc => { ((IDictionary<string,object>eo).Add(dc.ColumnName, r[dc]); return true; }))
select eo).Cast<dynamic>().ToList();
Console.WriteLine(list[0].ID); //your first ID of your DataTable.
What do you think?
精彩评论