【发布时间】:2011-04-10 15:57:30
【问题描述】:
我有一个这样的对象模型:
public class Quantity
{
public decimal Weight { get; set; }
public decimal Volume { get; set; }
// perhaps more decimals...
public static Quantity operator +(Quantity quantity1, Quantity quantity2)
{
return new Quantity()
{
Weight = quantity1.Weight + quantity2.Weight,
Volume = quantity1.Volume + quantity2.Volume
};
}
}
public class OrderDetail
{
public Quantity Quantity { get; set; }
}
public class Order
{
public IEnumerable<OrderDetail> OrderDetails { get; set; }
}
现在我想在 Order 类上引入一个只读属性 TotalQuantity,它应该总结所有 OrderDetails 的数量。
我想知道是否有比这更好的“LINQ 方式”:
public class Order
{
// ...
public Quantity TotalQuantity
{
get
{
Quantity totalQuantity = new Quantity();
if (OrderDetails != null)
{
totalQuantity.Weight =
OrderDetails.Sum(o => o.Quantity.Weight);
totalQuantity.Volume =
OrderDetails.Sum(o => o.Quantity.Volume);
}
return totalQuantity;
}
}
}
这不是一个好的解决方案,因为它会通过 OrderDetails 迭代两次。并且不支持这样的事情(即使在 Quantity 类中提供了 + 运算符):
Quantity totalQuantity = OrderDetails.Sum(o => o.Quantity); // doesn't compile
有没有更好的方法在 LINQ 中构建总和?
(只是为了理论上的兴趣,一个简单的 foreach 循环当然也可以很好地完成它的工作。)
感谢您的反馈!
【问题讨论】: