Does `Any ()` force linq execution?

I have a request linq to entity

.

will Any()

force linq execution (for example ToList()

)?

+3


source to share


4 answers


There is a very good MSDN article, Classification of Standard Query Operators by Execution Method , which describes all the standard LINQ operators. As you can see from the table, it Any

is executed immediately (like all operators that return one value). You can always refer to this table if you have doubts about the way a statement is executed.



+11


source


It's easy to spot: Any () returns a simple bool. Since bool is always bool, and not IQueryable or IEnumerable (or any other type) that may have its own implementation, we must conclude that Any () must evaluate the returned boolean.



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

+1


source


Short question, short answer: Yes, it will.

To find out if any element of the list meets a given condition (or if there is any element at all), the list will need to be enumerated. Since MSDN states :

This method does not return any items in the collection. Instead, it determines if the collection contains any items. Source enumeration stops as soon as the result can be determined.

Deferred execution does not apply here because this method provides the enumeration result and not another IEnumerable

.

+1


source


Yes and no. The method any

will read elements from the source immediately, but it does not guarantee that it will read all elements.

The method any

will enumerate elements from the source, but only as many as necessary to determine the result.

Without any parameter, the method any

will try to read only the first element from the source.

With a parameter, the method any

will only read elements from the source until it finds one that satisfies the condition. All elements are read only from the source if no element satisfies the condition before the last element.

+1


source







All Articles