convert generic list to datatable using linq..?
17,349
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()
Author by
siva
Updated on June 05, 2022Comments
-
siva almost 2 years
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 about 11 years@EliGassert yep, especially when you working with databables - you even don't need to write any object shredders
-
Ryszard Dżegan about 11 yearsYes, with the assumption that
Employee
is aDataRow
. 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. -
Sergey Berezovskiy about 11 years@yBee nope, see the linked article which shows how custom
CopyToDataTable<T>
extension method implemented