Does the Any
method in LINQ iterated over the entire collection or return true when the first successful iteration occurs?
Asked
Active
Viewed 238 times
3 Answers
6
The Any
method will only iterate over the minimum number of elements necessary. As soon as it finds a matching element it will return immediately
It's roughly implemented as follows
public static bool Any<T>(this IEnumerable<T> enumerable, Func<T, bool> predicate) {
foreach (var cur in enumerable) {
if (predicate(cur)) {
return true;
}
}
return false;
}
In the worst case (none or last matching) it will visit all elements. In the best case (first matching) it will only visit 1

JaredPar
- 733,204
- 149
- 1,241
- 1,454
-
I was hoping that was the case, thanks. I was originally using `Count() > 0` and realized it was a very expensive operation. I rediscovered `Any` and have been using it everywhere.:) – Jordan Mar 14 '12 at 16:28
2
The latter - you can look at the code with ReSharper to verify that if you download a trial version.
As to whether Any is efficient - it's not when e.g. a Count property is available as an alternative. But it does arguably express intent well.

Stuart Golodetz
- 20,238
- 4
- 51
- 80
-
If the IEnumerable
is actually a List – Jordan Mar 14 '12 at 16:34does Count() use the list's Count property? -
That is true, but I'm working with sequences that haven't been realized yet. Actually, I'm writing a generic library of methods to supplement `Enumerable`. So I don't know what the given sequence is except that it implements `IEnumerable
`. I could ask of course, which is why I've asked the above. I am wondering whether I need to special case for `List – Jordan Mar 14 '12 at 16:39` and other types that have a `Count` or `Length` property. -
1If you're working with sequences that haven't been realized yet, make sure to take care over whether they're repeatable or not. Since `Any` has to read an element of the sequence to do its job, you have to be careful when applying it to non-repeatable sequences or you'll lose the first element. I was having a look at this a while back actually in case it helps: http://stackoverflow.com/questions/9194908/safely-checking-non-repeatable-ienumerables-for-emptiness – Stuart Golodetz Mar 14 '12 at 18:08
-
1
Any returns true as soon as it finds a successful match to the predicate, though if none exist, it will have iterated across the entire collection.

Darren Kopp
- 76,581
- 9
- 79
- 93