# List<T> Any vs Count, which one is better for readability?

Resharper thinks I should change this

while (dockPanel.Contents.Count() > 0)


to the following:

while (dockPanel.Contents.Any())


Without thinking twice about it, I switched to the any version because .Any() is more readable for me. But a coworker of mine sees the change and asked why I did it. I explained that this improves readability but his objection was the following:

• Any is an ambiguous word.
• People may not be familiar with LINQ, so they might not be aware of what Any does at first glance.
• Count > 0 is universal. You don't have to know C# to find out what you're trying to do.

The confusion is probably compounded by the fact that I'm working overseas. People here speak little to no English here.

Which method should I stick with?

• “because I know ReSharper is smarter than me” I've had to disable several ReSharper's suggestions, because they actually produced code that I thought was less readable than the original. Jun 28, 2013 at 16:09
• The while (collection has elements) loop strikes me as odd. Presumably the collection is being emptied out as part of the loop body? Would it be clearer to use a foreach (item in collection) and then empty it at the end? Jun 28, 2013 at 18:36
• I find all three arguments to bogus. What I read from this is one grumped coder who can't handle to be corrected. Dec 6, 2013 at 20:29
• Note that .Count and .Count() are NOT the same thing when working with List<T>. Jun 17, 2015 at 8:38

It usually comes to me as "If there are any employees who are in the management role, then show a particular option panel".

And that means .Any(). Not .Count(). Very few times will I find myself using .Count() unless the underlying rule talks about "more than one" or "more than two" of something.

As a bonus, .Any() can be a performance enhancement because it may not have to iterate the collection to get the number of things. It just has to hit one of them. Or, for, say, LINQ-to-Entities, the generated SQL will be IF EXISTS(...) rather than SELECT COUNT ... or even SELECT * ....

I agree with Resharper and I'd go for the .Any() version.

The reason is that I associate .Count() with operations in which the number of elements actually matters while in your case you just need to check if there is at least one element.

On the opposite .Any() helps you communicate that you need to iterate until you have no more elements.

• «.Any() helps you communicate that you need to iterate until you have no more elements ». I don't think so: Doesn't any rather mean you'll stop iterating as soon as you find one match? Jun 28, 2013 at 16:35
• Poster probably meant "you need to iterate until you have no more elements that need to be filtered through". If it already has a match, then there is no need to filter through any more elements.
– JayC
Jul 5, 2013 at 7:39
• Any is perfect. "while there's anything there do this..." Feb 2, 2016 at 16:58