在单个查询中转换foreach

时间:2016-06-07 05:37:26

标签: c# linq

我有一个Linq查询和一个for循环,如:

double total = 0;

IEnumerable<Dispatch> requiredDispatches = Dispatches.Where(x => x.OrderId == SelectedOrder.OrderId);
foreach(Dispatch dispatch in requiredDispatches)
{
    total += dispatch.DispatchItemTransactions.Sum(x => x.Quantity);
}

我已经尝试了但只有一半:

total = Dispatches.Where(x => x.OrderId == SelectedOrder.OrderId)
                  .Select(x => x.DispatchItemTransactions).Sum( x => x.

但在x.后,它没有向我提供我的财产Quantity

1 个答案:

答案 0 :(得分:3)

您必须首先展平层次结构,使用SelectMany并查找Sum

var total = Dispatches.Where(x => x.OrderId == SelectedOrder.OrderId)
                      .SelectMany(x => x.DispatchItemTransactions)
                      .Sum( x =>x.Quantity);