聚合LINQ函数取代这个“accumalator”函数

时间:2015-06-06 11:01:07

标签: c# linq

所以我有这个功能:

var ordersInLast7Days = lineItems
                            .Where(x => x.OrderLogged > DateTime.Now.AddDays(-7))
                            .ToList();

ordersInLast7Days.ForEach(lineItem =>
{
    var qty = lineItem.Quantity;
    var pack = packs.FirstOrDefault(x => x.Id.Equals(lineItem.PackId));

    if (pack != null)
    {
        orderTotalsInLast7Days += qty * pack.Price;
    }
});

如何将其转换为收集Aggregate的{​​{1}} LINQ函数?

为了详细说明,我有3个这些函数都是相同的,所以只有guna有一个方法可以应用于所有qty * pack.Price

3 个答案:

答案 0 :(得分:1)

您可以使用Sum累积qty * pack.Price的总数,如下所示:

orderTotalsInLast7Days = ordersInLast7Days
    .Select(lineItem => new {
        qty = lineItem.Quantity
    ,   pack = packs.FirstOrDefault(x => x.Id.Equals(lineItem.PackId))
    })
    .Where(p => p.pack != null)
    .Sum(p => p.qty * p.pack.Price);

这是您的迭代代码的直接翻译,它使用匿名类型而不是局部变量。

答案 1 :(得分:1)

你可以这样做:

orderTotalsInLast7Days =
(
    from lineItem in lineItems
    where lineItem.OrderLogged > DateTime.Now.AddDays(-7)
    let qty = lineItem.Quantity
    from pack in packs.Where(x => x.Id.Equals(lineItem.PackId)).Take(1)
    select qty * pack.Price
).Sum();

答案 2 :(得分:1)

我同意dasblinkenlight,但提供使用聚合的解决方案:

var total = lineItems.Where(x => x.OrderLogged > DateTime.Now.AddDays(-7) && packs.Any(y => y.Id.Equals(x.PackId)))

.Aggregate(0, (res, item) => res += item.Quantity * packs.First(y => y.Id.Equals(item.PackId)).Price);