简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM