title: Buffering a LINQ query
body: <p><strong>FINAL EDIT</strong>:</p>
  
  <p>I've chosen <em>Timothy</em>'s answer but if you want a cuter implementation that leverages the C# <strong>yield</strong> statement check <em>Eamon</em>'s answer: <a href="https://stackoverflow.com/a/19825659/145757">https://stackoverflow.com/a/19825659/145757</a></p>
  
  <hr>
  
  <p>By default <strong>LINQ</strong> queries are <strong>lazily streamed</strong>.</p>
  
  <p><code>ToArray</code>/<code>ToList</code> give <strong>full buffering</strong> but first they're <strong>eager</strong> and secondly it may take quite some time to complete with an infinite sequence.</p>
  
  <p>Is there any way to have a combination of both behaviors : <strong>streaming</strong> and <strong>buffering</strong> values on the fly as they are generated, so that the next querying won't trigger the generation of the elements that have already been queried.</p>
  
  <p>Here is a basic use-case:</p>
  
  <pre><code>static IEnumerable&lt;int&gt; Numbers
  {
      get
      {
          int i = -1;
  
          while (true)
          {
              Console.WriteLine("Generating {0}.", i + 1);
              yield return ++i;
          }
      }
  }
  
  static void Main(string[] args)
  {
      IEnumerable&lt;int&gt; evenNumbers = Numbers.Where(i =&gt; i % 2 == 0);
  
      foreach (int n in evenNumbers)
      {
          Console.WriteLine("Reading {0}.", n);
          if (n == 10) break;
      }
  
      Console.WriteLine("==========");
  
      foreach (int n in evenNumbers)
      {
          Console.WriteLine("Reading {0}.", n);
          if (n == 10) break;
      }
  }
  </code></pre>
  
  <p>Here is the output:</p>
  
  <pre><code>Generating 0.
  Reading 0.
  Generating 1.
  Generating 2.
  Reading 2.
  Generating 3.
  Generating 4.
  Reading 4.
  Generating 5.
  Generating 6.
  Reading 6.
  Generating 7.
  Generating 8.
  Reading 8.
  Generating 9.
  Generating 10.
  Reading 10.
  ==========
  Generating 0.
  Reading 0.
  Generating 1.
  Generating 2.
  Reading 2.
  Generating 3.
  Generating 4.
  Reading 4.
  Generating 5.
  Generating 6.
  Reading 6.
  Generating 7.
  Generating 8.
  Reading 8.
  Generating 9.
  Generating 10.
  Reading 10.
  </code></pre>
  
  <p>The generation code is triggered 22 times.</p>
  
  <p>I'd like it to be triggered 11 times, the first time the enumerable is iterated.</p>
  
  <p>Then the second iteration would benefit from the already generated values.</p>
  
  <p>It would be something like:</p>
  
  <pre><code>IEnumerable&lt;int&gt; evenNumbers = Numbers.Where(i =&gt; i % 2 == 0).Buffer();
  </code></pre>
  
  <p>For those familiar with <strong>Rx</strong> it's a behavior similar to a <code>ReplaySubject</code>.</p>