如何对列表中所有共享特定属性的项目求和? [英] How to sum a set of items in a list that all share a specific property?
问题描述
我有一个对象列表.每个对象都有一组变量/属性.这些由多个十进制数和状态的字符串表示形式组成.如何将状态相同的对象列表中的每个金额相加?
I have a list of objects. Each object has a set of variables/properties. These consist of multiple decimal amounts and a string representation of a state. How would I sum each amount in the list of objects that has the same state?
我知道我可以执行 Model.ReportList.Sum(x => x.Amount)
来获取整个列表中所有Amount变量的总和.我想做同样的事情,但是只求和每个都具有的 x
的 Amount
变量,例如, x.State ="GA"
.
I know I can do Model.ReportList.Sum(x => x.Amount)
to get the sum of all Amount variables across the whole list. I want to do the same thing but only sum the Amount
variables of each x
that all have, for example, x.State = "GA"
.
推荐答案
使用 GroupBy
可能是一个很好的答案,但是如果您只在乎,那就太过分了汇总一个州的金额.如果这是您所需要的(如您的问题所提示),请使用 Where
扩展名:
Using GroupBy
may be a good answer, but it's overkill if you only care about summing amounts for one state. If that's what you need (as your question suggests), use Where
extension instead:
Model.ReportList.Where(x => x.State == "GA").Sum(x => x.Amount);
这篇关于如何对列表中所有共享特定属性的项目求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!