【问题标题】:Group by two columns in DataTable Column sum按DataTable Column sum中的两列分组
【发布时间】:2011-12-17 04:07:32
【问题描述】:

在以下代码中用于查找 DataTable dt 中 Rate 列的总和:

dt.Compute("Sum(Convert(Rate, 'System.Int32'))");

在这种情况下,可以像 SQL Inn 这样按子句分配分组,以便根据同一 dt Fo 的另一列中的值获取 Sum,例如:

----------------------------
Rate | Group  |type
----------------------------
100  | A      | 1
120  | B      | 2
70   | A      | 1
50   | A      | 2
----------------------------

我只是想得到。

Sum A=170(type-1) SUMA=50(type-2) an Sum B=120(type-2)

参考:我在上一个问题中的单列案例中得到了答案 Group by in DataTable Column sum.

【问题讨论】:

  • 你能解释一下为什么var sum1 = dt.Compute("Sum(Convert(Rate, 'System.Int32'))", "type = 1") 不适合你吗?
  • @GertArnold:需要检查两个条件组和类型
  • 所以使用“AND”。 (msdn.microsoft.com/en-us/library/…)

标签: c# winforms dictionary datatable


【解决方案1】:

您可以按匿名类型分组:

var result = from r in dt.AsEnumerable()
             group r by new { Group = r["Group"], Type = r["Type"] } into g
             select new { Group = g.Key.Group, 
                          Type = g.Key.Type, 
                          Sum = g.Sum(x => Convert.ToInt32(x["Rate"])) };

foreach (var r in result)
{
    Console.WriteLine("Group {0}, Type {1}, Sum {2}", r.Group, r.Type, r.Sum);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多