如何在Linq中获得SUM? [英] how to get a SUM in Linq?
本文介绍了如何在Linq中获得SUM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要执行以下操作,我有一个List
,其类包含2个整数id和count
I need to do the following, I have a List
with a class which contains 2 integer id and count
现在我要执行以下linq查询:
Now I want to do the following linq query:
get the sum of the count for each id
,但是可能会有具有相同ID的商品,因此应将其夏季化,例如:
but there can be items with the same id, so it should be summerized e.g.:
id=1, count=12
id=2, count=1
id=1, count=2
可能是:
id=1 -> sum 14
id=2 -> sum 1
该怎么做?
推荐答案
Group the items by Id
and then sum the Count
s in each group:
var result = items.GroupBy(x => x.Id)
.Select(g => new { Id = g.Key, Sum = g.Sum(x => x.Count) });
这篇关于如何在Linq中获得SUM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文