总结只包含与LINQ数值属性对象的集合 [英] Sum a collection of objects which contain numeric properties only with LINQ

查看:121
本文介绍了总结只包含与LINQ数值属性对象的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的对象模型:

I have an object model like this:

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; }
}

现在我想介绍一个只读属性 TotalQuantity 订单类,它应该总结所有的数量订单明细。

Now I want to introduce a readonly property TotalQuantity on the Order class which should sum up the quantities of all OrderDetails.

我想知道是否有更好的LINQ办法比这样的:

I am wondering if there is better "LINQ way" than this:

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;
        }
    }
}

这不是因为它通过订单明细迭代两次很好的解决方案。并且不支持这样的事情(即使+运算符的数量级提供):

It's not a nice solution as it iterates twice through the OrderDetails. And something like this is not supported (even though a + operator is provided in the Quantity class):

Quantity totalQuantity = OrderDetails.Sum(o => o.Quantity); // doesn't compile

有没有更好的方式来建立在LINQ的总和?

Is there a better way to build the total sum in LINQ?

(只为理论兴趣,一个简单的foreach循环也会做,当然它的工作做好。)

(Just for theoretical interest, a simple foreach loop would also do its job well of course.)

感谢您的反馈!

推荐答案

尝试:

OrderDetails.Select(o => o.Quantity).Aggregate((x, y) => x + y)

如果你preFER不要对每个除了(RE评论)的新产品数量​​对象的开销,你可以使用类似:

If you'd prefer not to have the overhead of the new Quantity object for each addition (RE comment), you could use something like:

new Quantity {
    Weight = OrderDetails.Select(o => o.Quantity.Weight).Sum(),
    Volume = OrderDetails.Select(o => o.Quantity.Volume).Sum()
};

不是像你一样的第一个,稍微笨拙(慢?)不仅仅是普通的的foreach 循环。

您可以找到更多关于骨料()方法的 MSDN上

You can find more about the Aggregate() method on MSDN.

这篇关于总结只包含与LINQ数值属性对象的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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