2016-06-07 28 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