使用LINQ计算总和 [英] Calculate sum using LINQ

查看:94
本文介绍了使用LINQ计算总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

foreach (Item item in Items)
                        {
                            Cost = Cost +
                                    item.Costs.OrderByDescending(x => x.ID)
                                              .FirstOrDefault()
                                              .Cost;

                        }

上面的LINQ返回150.

The above LINQ returns 150.

我有4个项目(1,2,3,4),各自具有成本.我需要重写上面的LINQ以获得正确的总成本210.

I have 4 items(1,2,3,4) with the respective Cost. I need to rewrite the above LINQ to get the correct total cost of 210.

ID--项目ID--费用

ID--ItemID-- Cost

11-1-10

21-2-20

31-2-30

41-3-40

51-3-50

61-4-60

任何人都可以提供经过修改的LINQ吗?

Can anyone please provide the modified LINQ to do so?

如下所示修改LINQ并不能给我预期的结果-

Modifying the LINQ as below doesnt give me the expected result --

foreach (Item item in Items)
                    {
                        Cost = Cost +
                                item.Costs.Sum(r => r.Cost);
                    }

推荐答案

我不确定为什么要先循环然后在循环中再次编写查询来弄乱它.用foreach循环或类似这样的LINQ查询来做到这一点:-

I am not sure why you are messing it up by looping first and writing a query again in the loop. Do it either with a foreach loop or a LINQ query like this:-

int result = items.Sum(x => x.Cost);

它将为您提供210作为输出.

It will give you 210 as output.

这篇关于使用LINQ计算总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆