Brady Moritz
Brady Moritz

Reputation: 8903

Check if List<T> has any values without calling Count?

I'm curious if I'm overlooking something obvious: I often use List<T>, and I often need to check if it contains any values or not. I call List<T>.Count() to see if the count is greater than 0. This feels like an expensive operation to perform for just wanting to see if it contains any values.

Is there some overlooked method for checking this? A IsEmpty() kind of thing?

Upvotes: 2

Views: 135

Answers (2)

Moti Azu
Moti Azu

Reputation: 5442

You can use

list.Any()

But this operation is just as cheap when you are actually dealing with a list. If it's a collection that implements IEnumerable but not IList, using Any will be cheaper.

Upvotes: 7

Darin Dimitrov
Darin Dimitrov

Reputation: 1039080

This feels like an expensive operation to perform for just wanting to see if it contains any values.

Don't worry, the .Count() extension method will fallback to the .Count property if the underling type supports it.

Of course if at compile time you have an IList<T> then you'd better directly use the .Count property. But if you only have an IEnumerable<T> (whose concrete implementation happens to be a List<T>) you could use the .Count() extension method without any performance problems.

Upvotes: 4

Related Questions