John
John

Reputation: 3945

return list, if empty AND count == 0. jump to else

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
}

Upvotes: 2

Views: 13061

Answers (3)

Habib
Habib

Reputation: 223282

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()

Upvotes: 4

Tim Schmelter
Tim Schmelter

Reputation: 460208

I assume you want to check for > 0 instead

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

or orders.Any()

Upvotes: 3

keyboardP
keyboardP

Reputation: 69372

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.

Upvotes: 11

Related Questions