如何在Linq中获得总和?

16

我需要做以下操作,我有一个包含两个整数 id 和 count 的类 List

现在我想执行以下的linq查询:

get the sum of the count for each id

但是可能存在具有相同id的项目,因此应进行汇总,例如:

id=1, count=12
id=2, count=1
id=1, count=2
抱歉,我只能回答英文问题。如果您有任何英文问题需要帮助,请随时提问。
id=1 -> sum 14
id=2 -> sum 1

如何做到这一点?


101 LINQ示例:http://code.msdn.microsoft.com/LINQ-Aggregate-Operators-c51b3869#CountConditional - Morten Frederiksen
3个回答

26

Id对项目进行分组,然后在每个组中求和Count值:

var result = items.GroupBy(x => x.Id)
                  .Select(g => new { Id = g.Key, Sum = g.Sum(x => x.Count) });

如果我不想使用新的,只是简单地总结一下,然后获取我之前拥有的对象,我该怎么做? - gurehbgui
你期待的结果是什么?类似于{Item = {id=1, count=12}, Sum=14}这样的吗? - Caramiriel
1
@Caramiriel 是的,看起来他想要创建与原始元素相同类型的新项目,并将它们的计数设置为总数,例如:var result = items.GroupBy(x => x.Id).Select(g => new HisType {id = g.Key, count = g.Sum(x => x.Count) }); - Matthew Watson

3

The following program...

struct Item {
    public int Id;
    public int Count;
}

class Program {

    static void Main(string[] args) {

        var items = new [] {
            new Item { Id = 1, Count = 12 },
            new Item { Id = 2, Count = 1 },
            new Item { Id = 1, Count = 2 }
        };

        var results =
            from item in items
            group item by item.Id
            into g
            select new { Id = g.Key, Count = g.Sum(item => item.Count) };

        foreach (var result in results) {
            Console.Write(result.Id);
            Console.Write("\t");
            Console.WriteLine(result.Count);
        }

    }

}

...打印:

1       14
2       1

3

试一下,

 .GroupBy(x => x.id)
 .Select(n => n.Sum(m => m.count));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接