我有以下每個循環來獲得所有子對象的總和。有沒有更好的方式使用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);
}
參考:
How to get the sum of the volume of highest and lowest priced items in linq
Using the ALL operator in linq to filter child items of EntitySet
我正在使用FirstOrDefault來確保即使存在多個項目,我也不會發生異常。使用SingleOrDefault會提高性能嗎? – Lijo 2012-07-27 13:18:20
@Lijo:很可能不會 - 但是不會出現多個具有相同ID的項目表明存在嚴重的數據問題,表明最好是保釋而不是在未知的領域繼續保留? – 2012-07-27 13:36:10