Is there any way one can apply a function with signature
bool IsOdd(int number);
to an array of integers and return whether any given integer in that array is odd in a single instruction? I know I can use
return (array.Where(IsOdd).Count() > 0);
but that implies calling two methods and making a comparison… Isn’t there really a shorter way to achieve the same?
Yes.
To start with you could use the form of
Countwhich takes a predicate:… but you don’t want to do that. That code is still expressing a numerical comparison which is unnecessary. You want to ask if any item in the array is odd. In other words:
Not only is this more expressive – it’s also potentially much faster. As soon as
Anyfinds a match, it will returntrue– whereasCountwould have to iterate over the whole array to find out exactly how many matches there are.Basically, whenever you see a LINQ query using
Count() > 0you should think about usingAnyinstead. In some cases with expression-tree-based queries such as LINQ to SQL it may not make a performance difference (if the query optimizer has visibility of the comparison with 0) but in LINQ to Objects it certainly can.