2011-05-12 265 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