Generating a n-ary Cartesian product example

后端 未结 2 1859
执念已碎
执念已碎 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:33

    Since List is IEnumerable, then your problem using Eric's solution is solved as follows:

    var collections = new List>();
    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);
    }
    

提交回复
热议问题