title: Generating a n-ary Cartesian product example
body: <p>I found that Eric Lippert's post <a href="https://stackoverflow.com/a/3098381/720616">here</a> suits a particular problem I have.</p>
  
  <p>The problem is I can't wrap my head around how I should be using it with a 2+ amount of collections.</p>
  
  <p>Having</p>
  
  <pre><code>var collections = new List&lt;List&lt;MyType&gt;&gt;();
  foreach(var item in somequery)
  {
      collections.Add(
              new List&lt;MyType&gt; { new MyType { Id = 1} .. n }
          );
  }
  </code></pre>
  
  <p>How do I apply the cartesian product linq query on the <em>collections</em> variabile ?</p>
  
  <p>The extension method is this one:</p>
  
  <pre><code>static IEnumerable&lt;IEnumerable&lt;T&gt;&gt; CartesianProduct&lt;T&gt;(this IEnumerable&lt;IEnumerable&lt;T&gt;&gt; sequences)
  {
      IEnumerable&lt;IEnumerable&lt;T&gt;&gt; emptyProduct = new[] { Enumerable.Empty&lt;T&gt;()};
      return sequences.Aggregate(
          emptyProduct,
          (accumulator, sequence) =&gt; 
              from accseq in accumulator 
              from item in sequence 
              select accseq.Concat(new[] {item})                       
          );
   }
  </code></pre>
  
  <p>Here is Eric's example for 2 collections:</p>
  
  <pre><code>var arr1 = new[] {"a", "b", "c"};
  var arr2 = new[] { 3, 2, 4 };
  var result = from cpLine in CartesianProduct(
                       from count in arr2 select Enumerable.Range(1, count)) 
               select cpLine.Zip(arr1, (x1, x2) =&gt; x2 + x1);
  </code></pre>