Playing With Any vs. Count() greater-than 0 in .Net (Enumerable Extensions)

Anyone who has encountered the differences between Any() and Count() > 0 in .NET has had to choose which one fits the particular circumstance.  This posting is an example of what each will do.

I recently ran across a situation where I need a program to "run as many as possible" followed by "only take the next action if the result is more than one".

At first, I had coded it with Any() then realized it WOULD always terminate at the first success, which was NOT what I wanted for the target program.  Even though ONE is considered success, I wanted AS-MANY-AS-POSSIBLE.  Being early morning, I wanted a visual example of this happening, so I wrote this code:

As Erik pointed out:  Using Count() > 0 has side-effects.
It was my intention to "exploit the side-effect".
I do have a C/C++ background -- languages where side-effects are exploited by design and practice, but those practices should not be carried forward into LINQ and other functional programming paradigms.

posted @ Saturday, October 5, 2013 9:19 AM
Print

Comments on this entry:

# re: Playing With Any vs. Count() greater-than 0 in .Net (Enumerable Extensions)

Left by Erik at 10/6/2013 4:39 AM
Gravatar
.Count() > 0 shouldn't be used instead of .Any(). The problem you've got here is that you have side effects to the Linq query that you rely on. Linq queries should not have side effects. E.g. that's the reason why there's no built in .Each() method.

# SIDE EFFECTS

Left by Tom Hines at 10/7/2013 8:43 AM
Gravatar
Erik, you are correct: It should not be used instead of Any(). I should have mentioned it was my intention to "exploit the side-effect" -- which can be bad (if unintended) and/or should be avoided. The spirit and intention of functional programming is to eliminate or avoid side-effects.

# re: Playing With Any vs. Count() greater-than 0 in .Net (Enumerable Extensions)

Left by Dusty Doors at 5/5/2016 9:11 AM
Gravatar
This is very useful, thanks.

Your comment:



(not displayed)

 
 
 
 

Live Comment Preview: