0

How to achieve this below datatable to a generic list conversion ?

I am trying this:

List<Emp> lstEmp= new List<Emp>(from prod in MyDatatable.AsEnumerable<Emp>() select prod);
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
user2519971
  • 345
  • 3
  • 12
  • 27
  • [How do you convert a DataTable into a generic list?](http://stackoverflow.com/questions/208532/how-do-you-convert-a-datatable-into-a-generic-list) – huMpty duMpty Dec 20 '13 at 09:23
  • @huMptyduMpty: but Jon Skeets answer does not answer this question. OP wants to initialite a custom class from the `DataRow` and create a `List` of it. – Tim Schmelter Dec 20 '13 at 09:24
  • @TimSchmelter: Not the Jons answer... there are other answers which does this! – huMpty duMpty Dec 20 '13 at 09:25

2 Answers2

3
var empList = MyDatatable.AsEnumerable().Select( row => 
   new Emp
   {
       Name= row.Field<string>("Name") // set the properties accordingly 
   }).ToList();
Damith
  • 62,401
  • 13
  • 102
  • 153
0

try this,

List<Emp> target = dt.AsEnumerable()
     .Select(row => new Emp
     {
         Name = row.Field<string>("Name")
     }).ToList();
Manish Sharma
  • 2,406
  • 2
  • 16
  • 31
  • Actually does it really require to specify every field. I want to skip this if LINQ can do this. Just to avoiding this for every field : Name= row.Field("Name") OR Name = String.IsNullOrEmpty(row.Field(1))... – user2519971 Dec 20 '13 at 10:50
  • you can use filed name too, instead of (1). – Manish Sharma Dec 20 '13 at 12:04