[英]linq to group by country and then sum of dynamic generated columns
My datatable
looks like this.. 我的
datatable
看起来像这样..
-Fix colms--- -----This Columns are dynamic created not fix ---
| | | |
Country Partners JAN-1990 FEB-1990 SEP-1990 . . . . . DEC-1995
----------------------------------------------------------------------------
-> India US 55.00 - 45.50 -
| Spain UK 43.54 12.23 - -
| Japan India 46.45 55.45 40.00 -
|-> India UK 45.50 54.65 21.20 85.36
And i need output like this.. 我需要这样的输出。
Country JAN-1990 FEB-1990 SEP-1990 . . . . . DEC-1995
-----------------------------------------------------------------
India 100.50 54.65 66.70 85.36
Spain 43.54 12.23 - -
Japan 46.45 55.45 40.00 -
i am using following linq query
to group countries but don't know how to get sum of grouping countries.. 我正在使用以下
linq query
对国家/地区进行分组,但不知道如何对国家/地区进行分组。
var result = from tab in dt.AsEnumerable()
group tab by tab["Country"]
into groupDt
select new
{
Country = groupDt.Key
};
Is it possible to group countries and sum of dynamic generated columns using linq ? 是否可以使用linq对国家和动态生成的列进行分组?
If any other possible solutions are appreciated. 如果有任何其他可能的解决方案,请予以赞赏。
Thanks in advance 提前致谢
This could work (assuming your dynamic columns are of type decimal
): 这可以工作(假设您的动态列的类型为
decimal
):
var dtResult = new DataTable();
dtResult.Columns.Add("Country", typeof(string));
foreach (var col in dt.Columns.Cast<DataColumn>().Skip(2))
{
dtResult.Columns.Add(col);
}
var countryGroups = dt.AsEnumerable().GroupBy(r => r.Field<string>("Country"));
foreach (var countryGroup in countryGroups)
{
DataRow row = dtResult.Rows.Add();
row.SetField("Country", countryGroup.Key);
foreach (var col in dtResult.Columns.Cast<DataColumn>().Skip(1))
{
row.SetField(col, countryGroup.Sum(g => g.Field<decimal>(col)));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.