Tuesday, June 7, 2016

Convert DataTable to List <T> using LINQ

The code below converts a DataTable object to generic list object. It assumes that the DataTable columns match with class properties.
C# Code
1
2
3
4
5
6
7
8
var personEnumerable = table.AsEnumerable();
List<Person> ListPosition = new List<Person>();
ListPosition = (from item in personEnumerable
            select new Person
            {
                ID = item.Field<int>("ID").ToString(),
                Salary = item.Field<double>("Salary").ToString()
            }).ToList();

Class
1
2
3
4
5
public class Person
{
    public string ID { get; set; }
    public string Salary { get; set; }
}

0 comments:

Post a Comment