siva
siva

Reputation: 61

convert generic list to datatable using linq..?

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..!

Upvotes: 2

Views: 17960

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

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()

Upvotes: 9

Related Questions