title: Is LINQ lazy-evaluated?
body: <p>Greetings, I have the following question. I did not find the exact answer for it, and it's really interesting to me. Suppose I have the following code that retrieves the records from database (in order to export it to XML file, for example).</p>
  
  <pre><code>var result = from emps in dc.Employees
    where emps.age &gt; 21
    select emps;
  
  foreach (var emp in result) {
    // Append this record in suitable format to the end of XML file
  }
  </code></pre>
  
  <p>Suppose there is a million of records that satisfy the <strong>where</strong> condition in the code. What will happen? All this data will be retrieved from SQL Server immediately to the runtime memory when it reaches the <em>foreach</em> construct, or it will be retrieved then necessary, the first record, second. In other words, does LINQ really handle the situation with iterating through large collections (see my <a href="https://stackoverflow.com/questions/1088442/what-is-the-purpose-advantage-of-using-yield-return-iterators-in-c/2508429#2508429" title="post">post</a> here for details)? </p>
  
  <p>If not, how to overcome the memory issues in that case? If I really need to traverse the large collection, what should I do? Calculate the actual amount of elements in collection with help of Count function, and after that read the data from the database by small portions. Is there an easy way to implement paging with LINQ framework?</p>