简体   繁体   English

如何在Linq中获得SUM?

[英]how to get a SUM in Linq?

I need to do the following, I have a List with a class which contains 2 integer id and count 我需要执行以下操作,我有一个包含一个包含2个整数id和count的类的List

Now I want to do the following linq query: 现在,我想执行以下linq查询:

get the sum of the count for each id

but there can be items with the same id, so it should be summerized eg: 但可能会有具有相同ID的商品,因此应将其夏季化,例如:

id=1, count=12
id=2, count=1
id=1, count=2

sould be: 乐于:

id=1 -> sum 14
id=2 -> sum 1

how to do this? 这该怎么做?

Group the items by Id and then sum the Count s in each group: Id对项目进行分组 ,然后将每组中的Count 相加

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

Try it , 试试吧 ,

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

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);
        }

    }

}

...prints: ...打印:

1       14
2       1

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

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