Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The output is <code>2,4,6,8</code> because of <a href="http://msdn.microsoft.com/en-us/library/bb943859.aspx" rel="noreferrer">deferred execution</a>.</p> <blockquote> <p>The query is actually executed when the query variable is iterated over, not when the query variable is created. This is called deferred execution.</p> <p>-- Suprotim Agarwal, <a href="http://www.dotnetcurry.com/ShowArticle.aspx?ID=750" rel="noreferrer">"Deferred vs Immediate Query Execution in LINQ"</a></p> </blockquote> <p>There is another execution called <a href="http://msdn.microsoft.com/en-us/library/bb738633.aspx" rel="noreferrer">Immediate Query Execution</a>, which is useful for caching query results. From Suprotim Agarwal again:</p> <blockquote> <p>To force immediate execution of a query that does not produce a singleton value, you can call the <code>ToList(), ToDictionary(), ToArray(), Count(), Average()</code> or <code>Max()</code> method on a query or query variable. These are called conversion operators which allow you to make a copy/snapshot of the result and access is as many times you want, without the need to re-execute the query.</p> </blockquote> <p>If you want the output to be <code>2,4,6</code>, use <a href="http://msdn.microsoft.com/en-us/library/bb342261.aspx" rel="noreferrer"><code>.ToList()</code></a>:</p> <pre><code>var list = new List&lt;int&gt;{1,2,4,5,6}; var even = list.Where(m =&gt; m%2 == 0).ToList(); list.Add(8); foreach (var i in even) { Console.WriteLine(i); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload