convert generic list to datatable using linq..?

siva picture siva · Feb 21, 2013 · Viewed 17.1k times · Source
List<Employee> objEmpList = new List<Employee>();
    for (int i = 0; i < 5; i++)
    { 
        objEmpList.Add(new Employee(){ID=i, Name="aa" + i});
    }

I want to create table with generic list items as rows using linq or lambda expressions...How to do that..??I did that using loops but I want do that using linq..!

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Feb 21, 2013

Use CopyToDataTable extension. See msdn article How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow

DataTable table = objEmpList.CopyToDataTable();

BTW here is simpler way to create list of employees:

Enumerable.Range(0,5)
          .Select(i => new Employee { ID = i, Name = "aa" + i })
          .ToList();

Consider also using NBuilder:

Builder<Employee>.CreateListOfSize(5).Build()