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.
public 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>andyield returnthe results. The overall performance wouldn’t increase but you could start faster to process the result.As a sample: