【问题标题】:linq to group by country and then sum of dynamic generated columnslinq 按国家/地区分组,然后动态生成列的总和
【发布时间】:2013-04-07 09:43:00
【问题描述】:

我的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

我需要这样的输出..

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             - 

我正在使用以下linq query 对国家/地区进行分组,但不知道如何获得分组国家的总和..

var result = from tab in dt.AsEnumerable()
             group tab by tab["Country"]
             into groupDt
             select new
             {
                Country = groupDt.Key
              };

是否可以使用 linq 对国家和动态生成的列进行分组?

如果有任何其他可能的解决方案表示赞赏。

提前致谢

【问题讨论】:

  • 这些列是如何自动生成的?
  • 通过存储过程。
  • 相同的程序用于两个不同的目的,所以我不能在那个 SP 中编辑。如果有其他可能性,他们让我知道。所以,我可以解决这个问题。

标签: asp.net linq c#-4.0 group-by


【解决方案1】:

这可行(假设您的动态列的类型为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)));
    }
}

【讨论】:

  • 感谢您的帮助。它可以帮助我通过一些更改来获得我的结果。
猜你喜欢
  • 1970-01-01
  • 2016-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 2012-06-18
  • 2011-08-14
相关资源
最近更新 更多