Use of .Any() in a C# List<> Explained

arrayclist

I've been discussing this with colleagues, and we couldn't figure out what the use is of .Any for any given List<>, in C#.

You can check the validity of an element in the array like the following statement:

if (MyList.Any()){ ...}  //Returns true or false

Which is exactly the same as

if (MyList.Count() != 0) { ... }

and is much more common, readable and clear about the intent of the if statement.

In the end, we were stuck with this thought:

.Any() can be used, will work just as well, but is less clear about
the intent of the programmer, and it that case it should not be used.

But we feel like this can't be right; we must be missing something.

Are we?

Best Answer

Keep in mind that Any doesn't operate on a List; it operates on an IEnumerable, which represents a concrete type that may or may not have a Count property. It's true that it's not necessarily the best thing to use on a List, but it definitely comes in handy at the end of a LINQ query. And even more useful than the standalone version is the override that takes a predicate just like Where. There's nothing built in on List that's anywhere near as convenient or expressive as the predicate-Any extension method.

Also, if you're using Count() (the LINQ extension method for IEnumerable), rather than Count (the property on List), it can have to enumerate the entire sequence if it can't optimize this away by detecting that your underlying data type has a Count Property. If you have a long sequence, this can be a noticeable performance hit when you don't really care about what the count is, and just want to know if there are any items in the collection.