Elad Benda
Elad Benda

Reputation: 36664

Does `Any()` forces linq execution?

I have a linq to entity query.

will Any() force linq execution (like ToList() does)?

Upvotes: 4

Views: 1755

Answers (4)

Guffa
Guffa

Reputation: 700592

Yes, and no. The any method will read items from the source right away, but it's not guaranteed to read all items.

The Any method will enumerate items from the source, but only as many as needed to determine the result.

Without any parameter, the Any method will only try to read the first item from the source.

With a parameter, the Any method will only read items from the source until it finds one that satisfies the condition. All items are only read from the source if no items satisfies the condition until the last item.

Upvotes: 2

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

There is very good MSDN article Classification of Standard Query Operators by Manner of Execution which describes all standard operators of LINQ. As you can see from table Any is executed immediately (as all operators which return single value). You can always refer this table if you have doubts about manner of operator execution.

Upvotes: 13

Spontifixus
Spontifixus

Reputation: 6660

Short question, short answer: Yes it will.

To find out if the any element of the list matches the given condition (or if there is any element at all) the list will have to be enumerated. As MSDN states:

This method does not return any one element of a collection. Instead, it determines whether the collection contains any elements. The enumeration of source is stopped as soon as the result can be determined.

Deferred execution does not apply here, because this method delivers the result of an enumeration, not another IEnumerable.

Upvotes: 1

Oskar Berggren
Oskar Berggren

Reputation: 5649

This is easy to discover: Any() returns a simple bool. Since a bool is always a bool, and not an IQueryable or IEnumerable (or any other type) that can have a custom implementation, we must conclude that Any() itself must calculate the boolean value to return.

The exception is of course if the Any() is used inside a subquery on a IQueryable, in which case the Linq provider will typically just analyse the presence of the call to Any() and convert it to corresponding SQL (for example).

Upvotes: 1

Related Questions