16

我需要执行以下操作,我有一个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

这个怎么做?

4

3 回答 3

26

将项目分组Id,然后将每组中的s相加:Count

var result = items.GroupBy(x => x.Id)
                  .Select(g => new { Id = g.Key, Sum = g.Sum(x => x.Count) });
于 2013-04-27T10:34:10.433 回答
3

试试看 ,

 .GroupBy(x => x.id)
 .Select(n => n.Sum(m => m.count));
于 2013-04-27T10:41:51.043 回答
3

以下程序...

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
于 2013-04-27T10:43:01.063 回答