[英]Refactor C# foreach Loop into Linq Statement
I have the following method containing a simple foreach loop in a C# class. 我有以下方法,在C#类中包含一个简单的foreach循环。 The method returns the sum of totals calculated using a function on a separate class. 该方法返回使用单独类上的函数计算出的总计的总和。
private readonly ICalculateTotalService _calculateTotalService;
public decimal GetTotal(IOrder order)
{
decimal paidTotal = 0;
foreach (var line in order.Lines)
{
paidTotal += _calculateTotalService.GetTotal(line);
}
return paidTotal;
}
Resharper is suggesting that this can be refactored into a LINQ statement. Resharper建议将其重构为LINQ语句。 What would the best way be to go about doing this? 最好的方法是执行此操作?
If IOrder.Lines
is IEnumerable
type or similar that supports LINQ: 如果IOrder.Lines
是IEnumerable
类型或支持LINQ的相似类型:
private readonly ICalculateTotalService _calculateTotalService;
public decimal GetTotal(IOrder order)
{
return order.Lines.Sum(line => _calculateTotalService.GetTotal(line));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.