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 co
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();
Since List<T>
is IEnumerable<T>
, then your problem using Eric's solution is solved as follows:
var collections = new List<List<MyType>>();
var product = collections.CartesianProduct();
foreach(var collection in product)
{
// a single collection of MyType items
foreach(var item in collection)
{
// each item of type MyType within a collection
Console.Write(item);
}
}
Of course you can aggregate the items from each collection in a more concise manner, for example as a single string
:
var product =
collections
.CartesianProduct()
.Select(xs => xs.Aggregate(new StringBuilder(), (sb, x) => sb.Append(x.ToString()), sb => sb.ToString()));
foreach(var collectionAsString in product)
{
Console.WriteLine(collectionAsString);
}