Reputation: 1803
I need to convert the data of a Typed DataTable to List of my entity. I've Mapped all the fields of entity with field of DataTable.
Any ideas?
Upvotes: 2
Views: 11378
Reputation: 1985
You could write an Extension Method:
public static List<TItem> Cast<TItem>(this DataRowCollection drc, Func<DataRow, TItem> converter)
{
List<TItem> list= new List<TItem>();
foreach (DataRow row in drc)
{
list.Add(converter(row));
}
return list;
}
Wherein converter is e.g. a lambda expression containing the following:
item => new YourClass(item)
Thanks,
Dennis
Upvotes: 0
Reputation: 6637
One way could be by doing it through custom code Lets suppose you Entity class name is 'MyEnt'
public class MyEnt
{
public string Name {get; set;}
public string Type {get; set;}
public LoadMyEnt(object [] array)
{
this.Name = array[0].ToString();
this.Type = array[1].ToString();
}
}
//for datatable, you could do
List<MyEnt> list = new List<MyEnt>();
foreach(DataRow dr in table.Rows)
{
MyEnt obj = new MyEnt();
obj.Load(dr.ItemArray);
list.Add(obj);
}
Upvotes: 2
Reputation: 18797
You can first convert it to generic datatable and then convert that datatable to list.
There are plenty of code snippets available to convert generic datatable to list. Some are:
How do you convert a DataTable into a generic list?
Convert DataTable to List<T>
Fastest way to convert datatable to generic list
Upvotes: 1
Reputation: 4822
I would check out AutoMapper which is a great tool that focus on these kind of scenarios.
Also here is guy that have done exactly your scenario.
Hope this was helpful!
Upvotes: 4