2

So I have a list of orders...and if the list is empty I want to to jump to the 'else.'

But because its a list (even if its empty) there still is an instance of it? right? anyway if there are no orders it still goes into the if statement so I tried adding .count == 0...

but it still goes into the if statement...what do I need to say where if there are no actual records in orders go to 'else....thanks for any replies

IEnumerable<OrderRecord> orders = _orderService.GetOrdersByCustomer(id, OrderStatus.Completed).ToArray();

if (orders != null && orders.Count() == 0 )
{
  //order exists
}
else
{
    //no order
}
Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
John
  • 3,965
  • 21
  • 77
  • 163

3 Answers3

11

You want to check if there are more than 0 items in the list

if (orders != null && orders.Count() > 0 )
{
    //order exists
}
else
{
    //no order
}

The list itself doesn't count as an item.

Or, as suggested by Richard Ev in the comments, you can use orders.Any which will return true if there are elements in the list.

keyboardP
  • 68,824
  • 13
  • 156
  • 205
  • 3
    Instead of `orders.Count() > 0`, consider using `orders.Any()`. `Any` has the benefit that it does not enumerate the entire collection, which can have a performance impact (if there is a large cost associated with creating an order). It is also arguably more "intentional". Also, it's less to type! :) – Richard Ev Jul 18 '13 at 14:32
  • @RichardEv - The flip side would be to simply use the `Count`/`Length` property, as it wouldn't invoke the enumerator at all (if performance was important). Having said that, I think `Any` is not only neater but also has a clear intention for anyone reading. – keyboardP Jul 18 '13 at 14:37
  • good point, I just scrolled right and spotted the `ToArray()` call in the code! – Richard Ev Jul 18 '13 at 14:38
  • @RichardEv: Even if it's better to use `Any` for readability, `Enumerable.Count` checks if the input sequence is a collection(like array or list), then it uses the `Count` property, `orders` is an array. – Tim Schmelter Jul 18 '13 at 14:56
4

You need to change your condition

orders.Count() == 0

To

orders.Count() > 0

since currently its check if the list contains no record.

You can also try Enumerable.Any like:

if(orders != null && order.Any())

See why its better to use Any in place of Count()

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
  • 1
    Even if it's better to use `Any` for readability, `Enumerable.Count` checks if the input sequence is a collection(like array or list), then it uses the `Count` property, `orders` is an array. – Tim Schmelter Jul 18 '13 at 14:55
  • @TimSchmelter, I agree, didn't see the `ToArray` part just concentrated on `So I have a list of orders` :) – Habib Jul 18 '13 at 14:57
3

I assume you want to check for > 0 instead

if (orders != null && orders.Count() > 0 )
{
  //order exists
}

or orders.Any()

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939