2012-07-27 39 views
3

我有以下每個循環來獲得所有子對象的總和。有沒有更好的方式使用LINQ?LINQ:有效的方式來獲得所有子項目的總和

Purchase p1 = db.Purchases.FirstOrDefault(p => p.PurchaseId == 1); 

int total = 0; 
foreach (SellingItem item in p1.SellingItems) 
{ 
    total = total + Convert.ToInt32(item.Price); 
} 

enter image description here

參考:

  1. How to get the sum of the volume of highest and lowest priced items in linq

  2. Using the ALL operator in linq to filter child items of EntitySet

回答

11

聲音就像你只是想:

// Any reason for FirstOrDefault rather than SingleOrDefault? 
var purchase = db.Purchases.FirstOrDefault(p => p.PurchaseId == 1); 

if (purchase != null) 
{ 
    var total = purchase.SellingItems 
         .Sum(x => Convert.ToInt32(x.Price)); 
    ... 
} 
// TODO: Work out what to do if there aren't any such purchases 

爲什麼你需要轉換的價格雖然? Price是什麼類型,爲什麼它不是正確的類型? (而這是否真的要int,而不是decimal?)

+0

我正在使用FirstOrDefault來確保即使存在多個項目,我也不會發生異常。使用SingleOrDefault會提高性能嗎? – Lijo 2012-07-27 13:18:20

+1

@Lijo:很可能不會 - 但是不會出現多個具有相同ID的項目表明存在嚴重的數據問題,表明最好是保釋而不是在未知的領域繼續保留? – 2012-07-27 13:36:10

3
p1.SellingItems.Sum(p => p.Price) 
1

嘗試使用LINQ的Sum方法:

Purchase p1 = db.Purchases.FirstOrDefault(p => p.PurchaseId == 1); 

int total = p1.SellingItems.Sum(item => Convert.ToInt32(item.Price)); 

這不是更有效,因爲它不會有任何更快。但它更簡潔。

+2

它可能會更快,如果這是在數據庫中完成的......不需要將數據拉回僅用於求和。 – 2012-07-27 12:33:56

+1

@JonSkeet好點。我只使用過Linq-to-Objects,而不是Linq-to-SQL – ColinE 2012-07-27 12:40:03

相關問題