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

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
siva
  • 61
  • 1
  • 3
  • 10

1 Answers1

9

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()
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • @EliGassert yep, especially when you working with databables - you even don't need to write any object shredders – Sergey Berezovskiy Feb 21 '13 at 14:11
  • Yes, with the assumption that `Employee` is a `DataRow`. Or maybe I don't anderstand the sentence in question. He want to create firstly rows from list of objects or these objects are data rows. – Ryszard Dżegan Feb 21 '13 at 14:15
  • @yBee nope, see the linked article which shows how custom `CopyToDataTable` extension method implemented – Sergey Berezovskiy Feb 21 '13 at 14:19