The Enumerable.Any<TSource>() is an extension method that lives in System.Core assembly under System.Linq namespace. If you are wondering what happens with the extended enumerable source then this is the right post.

In the right gets enumerated or not then we would have to look at the implementation. In System.Core 4.0.0.0 the Any(…) method comes with two overloads which is worth investigating.

Simply decompile the assembly in order to find the implementations of Any() methods. (I am using IL Spy).

Yes it makes sense, the enumeration of the source checks if there is a next item using MoveNext(), disposes the instance of the enumerator, then returns.

With the second overload, the behaviour is different. The performance of Any() depends on the predicate logic and the size of the source. Worst case scenario, the source is large and only the last item satisfies predicate logic, then the foreach loop will have to iterate through the whole source.

If by now you’re wondering what is the difference of Linq.Any() vs Linq.Count() > 0, then you are on the right thinking track. I’ll try to cover that in a future post, for now I bet StackOverflow has an answer.

Leave a Reply

Your email address will not be published. Required fields are marked *