简体   繁体   English

根据另一列的值汇总DataTable中的列值

[英]Sum up column values in DataTable based on the value of another column

I have a DataTable, like this: 我有一个数据表,像这样:

Amount | Count
-----------------------
20.0   | 2
42.0   | 1
78.0   | 5
91.0   | 2

I'd like to sum up the Count column, based on what's in the Amount column. 我想根据“ Amount列中的内容总结“ Count ”列。

I want to find the sum of Count for all Amount between 0 - 50 and 51-100, which would be 3 and 7 in this example. 我想找到介于0-50和51-100之间的所有AmountCount总和,在此示例中为3和7。

Is there a way to quickly get that data? 有没有一种快速获取该数据的方法?

Here's what I have currently: 这是我目前所拥有的:

foreach (int min in ranges)
{
    int max = min + 50;
    int count = 0;

    foreach (DataRow dr in dt)
    {
        if (dr["Amount"] > min && dr["Amount"] < max)
            count += dr["Count"];
    }
}

I'm looking for a more elegant solution 我正在寻找更优雅的解决方案

A good link for learning Linq is 101 Linq samples . 学习Linq的一个很好的链接是101个Linq样本 The following piece of code should give you a good starting point though it creates ranges from 0 to <50, 50 to <100 and so on. 尽管下面的代码创建的范围是0到<50、50到<100,依此类推,但它应该为您提供一个良好的起点。 It assumes that the ranges do have regular intervals. 假定范围确实有规则的间隔。

var dt = new DataTable();
dt.Columns.Add("Amount", typeof(int));
dt.Columns.Add("Count", typeof(int));
dt.Rows.Add(20, 2);
dt.Rows.Add(42, 1);
dt.Rows.Add(78, 5);
dt.Rows.Add(91, 2);
var result = from DataRow x in dt.Rows
                group x by ((int)x["Amount"]) / 50 into grp 
                select new {LowerBoundIncl = grp.Key * 50, 
                        UpperBoundExcl = (grp.Key + 1) * 50, 
                        TotalCount = grp.Sum(y => (int) y["Count"])};

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM