Generating a n-ary Cartesian product example

后端 未结 2 1860
执念已碎
执念已碎 2020-12-19 19:35

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

相关标签:
2条回答
  • 2020-12-19 20:18

    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();
    
    0 讨论(0)
  • 2020-12-19 20:33

    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);
    }
    
    0 讨论(0)
提交回复
热议问题