Reputation: 21
Please advice how I can create a datatable with the following source:
public class MyClass : IEquatable<My>
{
public int field1 { get; set; }
public int field2 { get; set; }
}
List<MyClass> lst = new List<MyClass>();
MyClass e = new MyClass;
e.field1 = 1;
e.field2 = 2;
lst.Add(e);
How I can create the datatable for field1 and field2 values using Linq ?
Upvotes: 1
Views: 89
Reputation: 63065
You can Use CopyToDataTable extension Method. Check MSDN article How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow
DataTable table = lst.CopyToDataTable();
Upvotes: 1
Reputation: 6670
Unfortunately you can't use any cool LINQ specific code but you can create a DataTable, add the Columns, loop over the List you've populated
DataTable dt = new DataTable();
dt.Columns.Add("field1");
dt.Columns.Add("Field2");
lst.ForEach(l => {
var dr = dt.NewRow();
dr[0] = l.field1;
dr[1] = l.field2;
dt.Rows.Add(dr);
});
Upvotes: 1