Reputation: 269
I would like to write a Linq
query to apply group-by on DataTable
, which outputs the result as a DataTable
.
I tried this code, which returns a result as var
type, but I want the result in DataTable
var query = from row in dt.AsEnumerable()
group row by row.Field<DateTime>("ExpDate").Year into grp
select new
{
Years = grp.Key,
RSF = grp.Sum(r => r.Field<decimal>("SpaceRSF"))
};
Please could you assist me in finding a proper answer.
Upvotes: 1
Views: 1820
Reputation: 236218
Look at How to: Implement CopyToDataTable - this topic describes how to implement two custom CopyToDataTable extension methods that accept a generic parameter T of a type other than DataRow.
Just use code from that article (ObjectShredder<T>
) to achieve following result:
DataTable table = query.CopyToDataTable();
Upvotes: 2
Reputation: 4567
ok, so according to this
select new
{
Years = grp.Key,
RSF = grp.Sum(r => r.Field<decimal>("SpaceRSF"))
};
code which return result as var type
effectively returns collection of objects having two properties: Years
and RSF
.
If you want to have datatable instead, then write the code that puts all the data into the datatable. Basically, it might look similarly as following:
DataTable table = new DataTable();
table.Columns.Add("Years");
table.Columns.Add("RSF");
foreach(var item in query)
{
table.Add(item.Years, items.RSF)
}
Hope this helps.
Upvotes: 0