title: Implementation of WhereListIterator.ToList()
body: <p>In a piece of code like</p>
  
  <pre><code>List&lt;int&gt; foo = new List&lt;int&gt;() { 1, 2, 3, 4, 5, 6 };
  IEnumerable&lt;int&gt; bar = foo.Where(x =&gt; x % 2 == 1);
  </code></pre>
  
  <p><code>bar</code> is of type <code>System.Linq.Enumerable.WhereListIterator&lt;int&gt;</code> due to deferred execution. Since it implements <code>IEnumerable&lt;int&gt;</code> it is possible to convert it to a <code>List&lt;int&gt;</code>using <code>ToList()</code>. However, I have been unable to identify some parts of the code that is run when <code>ToList()</code> is called. I am using dotPeek as a decompiler and this is my first time attempting such a thing, so correct me if i made any mistakes on the way.</p>
  
  <p>I will describe what I found so far below (All assemblies are Version 4.0.0.0):</p>
  
  <ol>
  <li><p><code>Enumerable.WhereArrayIterator&lt;TSource&gt;</code> is implemented in the file <code>Enumerable.cs</code> of the namespace <code>System.Linq</code> in the assembly <code>System.Core</code>. The class neither defines <code>ToList()</code> itself nor does it implement <code>IEnumerable&lt;TSource&gt;</code>. It implements <code>Enumerable.Iterator&lt;TSource&gt;</code> which is located in the same file. <code>Enumerable.Iterator&lt;TSource&gt;</code> does implement <code>IEnumerable&lt;TSource&gt;</code>.</p></li>
  <li><p><code>ToList()</code> is an extension mewthod that is also located in <code>Enumerable.cs</code>. All it  does is null checking and then calling the constructor of <code>List&lt;TSource&gt;</code> with its argument.</p></li>
  <li><p><code>List&lt;T&gt;</code> is defined in the file <code>List.cs</code> of the namespace <code>System.Collections.Generic</code> in the assembly <code>mscorlib</code>. The constructor that is called by <code>ToList()</code> has the signature <code>public List(IEnumerable&lt;T&gt; collection)</code>. It once again null checks and then casts the argument to <code>ICollection&lt;T&gt;</code>. If the collection has no elements, its creates a new list of an empty array, otherwise it uses the <code>ICollection.CopyTo()</code> method to create the new list.</p></li>
  <li><p><code>ICollection&lt;T&gt;</code> is defined in <code>mscorlib</code> \ <code>System.Collections.Generic</code> \ <code>ICollection.cs</code>. It implements <code>IEnumerable</code> in its generic and non-generic form.</p></li>
  </ol>
  
  <p>This is where I am stuck. Neither <code>Enumerable.WhereArrayIterator&lt;TSource&gt;</code> nor <code>Enumerable.Iterator&lt;TSource&gt;</code> implement <code>ICollection</code>, so somewhere, a cast has to happen and I am unable to locate the code that is run when <code>CopyTo()</code> is called.</p>