C# 如何在 Linq 中获得 SUM?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16250991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:33:01  来源:igfitidea点击:

how to get a SUM in Linq?

c#linq

提问by gurehbgui

I need to do the following, I have a Listwith a class which contains 2 integer id and count

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

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 e.g.:

但是可以有具有相同 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?

这该怎么做?

采纳答案by dtb

Groupthe items by Idand then sumthe Counts in each group:

将项目分组Id,然后对每组中的s求和Count

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

回答by zey

Try it ,

尝试一下 ,

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

回答by Branko Dimitrijevic

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