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?
2 Answers 2
For me, it's about intent. What does your code's business logic say if you read it in English (or your native language)?
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.
-
2\$\begingroup\$ «
.Any()
helps you communicate that you need to iterate until you have no more elements ». I don't think so: Doesn'tany
rather mean you'll stop iterating as soon as you find one match? \$\endgroup\$Nadir Sampaoli– Nadir Sampaoli2013年06月28日 16:35:34 +00:00Commented Jun 28, 2013 at 16:35 -
\$\begingroup\$ 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. \$\endgroup\$JayC– JayC2013年07月05日 07:39:56 +00:00Commented Jul 5, 2013 at 7:39
-
\$\begingroup\$ Any is perfect. "while there's anything there do this..." \$\endgroup\$Fattie– Fattie2016年02月02日 16:58:40 +00:00Commented Feb 2, 2016 at 16:58
.Count
and.Count()
are NOT the same thing when working withList<T>
. \$\endgroup\$