It doesn't query your database until you enumerate over the query or call ToList()
, ToArray()
, etc. This is called Deferred Execution.
Many of the Standard Query Operators return elements when iterated
over using the foreach statement. These operators essentially do no
work UNTIL the first element is requested, and then suspend until the
next element is requested. Until the returned query is iterated over,
no work is carried out internally for any of these statements. This
deferred execution allows you to control when and if potentially
lengthy work is carried out.
If you want a query to be realized immediately, call ToList, ToArray
or any of the other operators that need to enumerate the entire
sequence to return a result.
LINQ leverages a language feature added in C# 2.0 that made it simpler
when writing methods that returned one element at a time when iterated
over. The yield return statement essentially suspends a loop by
returning a value, picking up exactly where it left off next time a
MoveNext is called.
The MSDN library describes operators that use Deferred Execution as:
This method is implemented using deferred execution. The immediate
return value is an object that stores all the information required to
perform the action. The query represented by this method is not
executed until the object is enumerated either by calling its
GetEnumerator method directly or by using foreach in Visual C# or For
Each in Visual Basic.