Arpit Khandelwal
Arpit Khandelwal

Reputation: 1803

How to convert typed DataTable into List of Entity?

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

Answers (4)

Dennis Röttger
Dennis Röttger

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

FIre Panda
FIre Panda

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

Kamyar
Kamyar

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

Marcus Hammarberg
Marcus Hammarberg

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

Related Questions