Generating a n-ary Cartesian product example

.net, c#, cartesian-product, linq

Solution

The sample code is already able to do "n" cartesian products (it does 3 in the example). Your problem is that you have a `List<List<MyType>>` when you need an `IEnumerable<IEnumerable<MyType>>`

IEnumerable<IEnumerable<MyType>> result = collections
  .Select(list => list.AsEnumerable())
  .CartesianProduct();

Problem

I found that Eric Lippert's post here suits a particular problem I have. The problem is I can't wrap my head around how I should be using it with a 2+ amount of collections. Having ``` var collections = new List<List<MyType>>(); foreach(var item in somequery) { collections.Add( new List<MyType> { new MyType { Id = 1} .. n } ); } ``` How do I apply the cartesian product linq query on the collections variabile ? The extension method is this one: ``` static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>()}; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from accseq in accumulator from item in sequence select accseq.Concat(new[] {item}) ); } ``` Here is Eric's example for 2 collections: ``` 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) => x2 + x1); ```

Original source

Related problems