0

How to get rid of "If then else" ?

  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
arlen
  • 1,065
  • 1
  • 16
  • 31

1 Answers1

0

If the list is empty then Sum() will return null - so you could just return the sum:

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

In C# you could also use ?? to turn that into a zero instead of null if you wanted to

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

I'm not a VB user, but it looks like you can do this same null coallescing in VB using If - see Is there a VB.NET equivalent for C#'s '??' operator?

Community
  • 1
  • 1
Stuart
  • 66,722
  • 7
  • 114
  • 165
  • The select part of the query triggers the error, because the list is empty. I don't think that your query in c# gonna work too. because the list is empty so there is no values for the select part (x.Products.UnitCost -x.Products.SalePrice). – arlen May 12 '11 at 15:24
  • I'm confused - which list is empty? x.Products? What happens if you put the projection into the Sum - like `.Sum(Function(x) x.Products.UnitCost - x.Products.SalePrice)`? – Stuart May 12 '11 at 16:30