score:3
msdn documentation addresses this question under the deferred query execution section (emphasis mine).
in a query that returns a sequence of values, the query variable itself never holds the query results and only stores the query commands. execution of the query is deferred until the query variable is iterated over in a foreach or for each loop...
that narrows down the answer to options 2 and 3.
foreach
is just syntactic sugar, underneath the compiler re-writes that as a while loop. there's a pretty thorough explanation of what happens here. basically your loop will end up looking something like this
{
ienumerator<?> e = ((ienumerable<?>)model).getenumerator();
try
{
int m; // this is inside the loop in c# 5
while(e.movenext())
{
m = (?)e.current;
// your code goes here
}
}
finally
{
if (e != null) ((idisposable)e).dispose();
}
}
enumerator is advanced before it reaches your code inside the loop, so slightly before you get to @item.bar
. that only leaves option 2, the @foreach (var item in model)
line (though technically that line doesn't exist after the compiler is done with your code).
i'm not sue if the query will execute on the call to getenumerator()
or on the first call to e.movenext()
.
as @pst points out in the comments, there are other ways to trigger execution of a query, such as by calling tolist
, and it may not internally use a foreach
loop. msdn documentation sort of addresses this here:
the iqueryable interface inherits the ienumerable interface so that if it represents a query, the results of that query can be enumerated. enumeration causes the expression tree associated with an iqueryable object to be executed. the definition of "executing an expression tree" is specific to a query provider. for example, it may involve translating the expression tree to an appropriate query language for the underlying data source. queries that do not return enumerable results are executed when the execute method is called.
my understanding of that is an attempt to enumerate the expression will cause it to execute (be it through a foreach
or some other way). how exactly that happens will depend on the implementation of the provider.
score:-2
the work is deferred until it needs to be done. in your example, the query will run when it tries to get a value for item
.
score:2
as a point of clarification, linq to sql/entity framework evaluate the linq query expressions when the getenumerator is called. this is used under the covers by foreach, thus while it appears that deferred execution waits until the foreach happens, it is actually the getenumerator that foreach uses that really is the key execution point.
score:5
the query execution (i assume getall returns iqueryable) will be deferred into the view, and will be unwrapped on the foreach line, because that is the first place where you start iterating over the collection.
update for anybody interested, here's "proof". create a class like this:
public class diagnosticcollection<t> : system.collections.generic.list<t>
{
public new enumerator getenumerator()
{
debug.print("collection unwrap");
return base.getenumerator();
}
}
test it in your view like this:
@model playmvc.models.diagnosticcollection<string>
@{system.diagnostics.debug.print("before foreach");}
@foreach (var item in model)
{
system.diagnostics.debug.print("after foreach");
@item
}
Source: stackoverflow.com
Related Query
- Does LINQ deferred execution occur when rendering the view, or earlier?
- What does LINQ return when the results are empty
- How does deferred LINQ query execution actually work?
- Linq - What is the quickest way to find out deferred execution or not?
- linq deferred execution when using locks in methods that return IEnumerable
- How does LINQ defer execution when in a using statement
- Does this LINQ code perform multiple lookups on the original data?
- LINQ to Entities does not recognize the method 'Boolean HasFlag(System.Enum)' when creating the expression via System.Linq.Expressions.Expression
- How does linq actually execute the code to retrieve data from the data source?
- Refactor Linq code and "LINQ to Entities does not recognize the method"
- Does the C# LINQ Aggregate method finish execution once the result can no longer change?
- Getting the first result from a LINQ query - why does ElementAt<T>(0) fails when First<T>() succeeds?
- When selected into an object; does Linq To SQL still perform the logic in a SQL Query?
- When does this LINQ query go to the database?
- why does this linq code get exponentially slower when applying First() to projection?
- LINQ deferred execution with a function's result as source (e.g. Console.ReadLine)
- LINQ to Entities does not recognize the method 'System.String ToString()' method when converting Nullable DateTime
- How can I check the number of calls to the database in LINQ query when using .NET Core and Code First?
- LINQ and deferred execution when comparing with NULL
- Does Deferred Execution works in the same way for method syntax and query syntax in LINQ/Entity Framework?
- How do I create a linq query that returns the distinct 3 letter prefix of words in a list using deferred execution
- Why does this linq query fail when I change the select clause to select new Model
- How does the .All(db1 => db1.Text != wb.Text)) in LINQ work when comparing two lists?
- How can I ensure that my database connection will be closed with the deferred execution of a linq query?
- Specific linq exception when converting string to int. LINQ to Entities does not recognize the method 'Int32 ToInt32(System.Object)' m
- Does Linq in Entity Framework code first use SQL or does it get the whole table first?
- If result of the LINQ has an interface type it means it has a deferred execution
- Does Linq search the entire database when I run a select statement with a time restricting where clauses?
- Will LINQ to SQL use defered execution when we map the result to an object?
- When running a method that uses linq to get the palindromes from a string, why does SelectMany order the resulting strings?
More Query from same tag
- join multiple tables using LINQ
- can we build linq query over dynamically generated xml response?
- English Dictionary word matching from a string
- Performance difference / improvement with custom Linq extensions
- Linq query where any item from List<int> belongs to parameter string[]
- How to "zip" or "rotate" a variable number of lists?
- linq on a DataTable giver compilation error
- 2 dimensional array to object in C# linq to sql
- A better way than generic list of anonymous type
- Using a linq or lambda expression in C# return a collection plus a single value
- System.Linq.Dynamic dynamic column name and parameter
- MVC Pass Paramater from ActionLink to View to return Recordset
- Table not getting updated while using LinQ
- Linq - Expression.And to join N elements BinayExpression
- How ToLookup() with multiple indexes?
- Retrieve relational data using linq
- How can restrict data from an Included class with LINQ?
- How to determine if a string contains any matches of a list of strings
- find all records in datatable from another datatable
- LINQ start and stop segments in list of List<T> elements
- How to order a C# custom object collection based upon a list
- Linq to XML parsing
- datatable colum sum using linq in c#
- Parsing XML with LINQ
- Load related nested Entities of included List
- Code First Entity Framework Linq Statement Returning Missing Records
- How to do Linq to SQL dateTime Filter
- Check in list and Filter collection using Linq
- How to "Linq to DataTable" using Own DataTable Class
- Linq dynamic order query result by typed input string