title: Slow foreach() on a LINQ query - ToList() boosts performance immensely - why is this?
body: <p>I kind of grasp the whole delayed execution concept, but the following has me puzzled...</p>
  
  <p>On a DataTable containing about 1000 rows, I call <em>AsEnumerable()</em>. I then select the entities returned into an IEnumerable of strongly typed classes <strong>(1)</strong>... Here's where I get confused: I do a foreach loop on the collection; selecting stuff from the individual items in the collection using a bunch of <em>Where()</em> calls <strong>(2)</strong> ... And it's dead slow.
  <br />
  <br /></p>
  
  <ol>
  <li><code>DataTable.AsEnumerable().Select(r =&gt; new ObjectRepresentation { ... });</code></li>
  <li><code>item.Where(i =&gt; i.SomeEnum == SomeEnum.Something)</code></li>
  </ol>
  
  <p><br />
  ... But if I call <em>ToList()</em> right after my <em>AsEnumerable()</em> call on the DataTable, the foreach loop takes less than a second to complete.</p>
  
  <p>What am I missing here? Am I effectively calling <em>AsEnumerable()</em> each time my loop iterates? Or each time I access an item in the collection? Or each time I do a <em>Where()</em> call on an item in the collection? Or all the above?
  <br />
  <br />
  <br />
  <strong>Update</strong></p>
  
  <p>Somewhat complete code:</p>
  
  <pre><code>public class ObjectRepresentation
  {
      public SomeEnum SomeEnum { get; set; }
  }
  
  
  var collection = DataTable.AsEnumerable().Select(r =&gt; new ObjectRepresentation
  {
      SomeEnum = (SomeEnum)Convert.ToInt32(r["SomeEnum"])
  });
  
  foreach(var item in collection) // slow loop
  {
      // 10 or so Where() calls on item inside this loop
  }
  
  collection = collection.ToList(); // Hit hyper speed button!
  
  foreach(var item in collection) // fast loop
  {
      // 10 or so Where() calls on item inside this loop
  }
  </code></pre>