2016-06-07 40 views
0

我有一个LINQ查询和一个循环里面想:转换的foreach

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

回答

3

你必须首先扁平化层级,使用SelectMany他们寻找Sum

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

谢谢。这很好。 – Vishal