如何在Linq获得SUM?

时间:2013-04-27 10:29:12

标签: c# linq

我需要执行以下操作,我有一个List,其中一个类包含2个整数id和count

现在我想执行以下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

怎么做?

3 个答案:

答案 0 :(得分:24)

Group Id之后的项目,然后是sum每个组中的Count

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

答案 1 :(得分:3)

试试吧,

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

答案 2 :(得分:1)

以下计划......

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