C# – How to convert linq result to DataTable

c++linq

I have the following DataTable:

DataTable itemsOnSkid = new DataTable();
itemsOnSkid.Columns.Add("ItemNumber");
itemsOnSkid.Columns.Add("Qty");

And I need to aggregate this datatable by itemnumber. I'm using the following linq code:

var result =    from row in itemsOnSkid.AsEnumerable()
                group row by row.Field<string>("ItemNumber") into grp
                select new
                {
                    ItemNumber = grp.Key,
                    Qty = grp.Sum(r => r.Field<int>("Qty"))
                };

Problem is that I need to replace the first datatable with this result, but I'm not able to use .CopyToDataTable() on result.

How can I convert this result back to a datatable?

Best Solution

You can't use CopyToDataTable() in this case, since the thing you're copying from has to be a DataRow. I think you're stuck doing it manually.

DataTable items = new DataTable();
items.Columns.Add("number");
items.Columns.Add("qty");

var result = from r in items.AsEnumerable()
             group r by r.Field<string>("number") into grp
             select new {
                 number = grp.Key,
                 qty = grp.Sum(r => r.Field<int>("qty"))
             };

DataTable newItems = new DataTable();
newItems.Columns.Add("number");
newItems.Columns.Add("qty");

foreach (var item in result) {
    DataRow newRow = newItems.NewRow();
    newRow["number"] = item.number;
    newRow["qty"] = item.qty;
    newItems.AddRow(newRow);
}