2011-05-12 141 views
0

如何擺脫「If then else」?Linq to Entities

If qShoppingCartByCartID.Invoke(_context).Count > 0 Then 
      Return qShoppingCartByCartID.Invoke(_context).Select(Function(x) x.Products.UnitCost - x.Products.SalePrice).Sum 
     Else 
      Return 0 
     End If 

回答

0

如果列表爲空,則總和()將返回null - 所以你可以只返回總和:

Return qShoppingCartByCartID.Invoke(_context).Select(Function(x) x.Products.UnitCost - x.Products.SalePrice).Sum() 

在C#中,你也可以使用??來把它轉換成一個零,而不是空如果你想

return qShoppingCartByCartID....Sum() ?? 0; 

我不是一個VB的用戶,但它看起來像你可以在VB中使用If做同樣的空coallescing - 看Is there a VB.NET equivalent for C#'s '??' operator?

+0

查詢的select部分觸發錯誤,因爲列表爲空。我不認爲你在C#中的查詢也會工作。因爲列表是空的,所以沒有選擇部分的值(x.Products.UnitCost -x.Products.SalePrice)。 – arlen 2011-05-12 15:24:15

+0

我很困惑 - 哪個列表是空的? x.Products?如果將投影放入Sum中會發生什麼 - 例如'.Sum(Function(x)x.Products.UnitCost - x.Products.SalePrice)'? – Stuart 2011-05-12 16:30:09