N-Ary/Multiple-List Cartesian Product

谁说胖子不能爱 提交于 2020-12-26 04:26:06

问题


in Product SKUs, we can get Cartesian Product in the way of LINQ:

string[] arr1 = new[] {"red", "blue", "orange"};
string[] arr2 = new[] {"5 inche", "8 inch"};
var result = from a in arr1
             from b in arr2
             select a + " " + b;
foreach (var item in result){
    Console.WriteLine(item);
}

We know the exact number of arrays.

My question is: If the number of arrays is dynamic, how do we get Cartesian Product?

Thanks.


回答1:


I'd put them in a list of string arrays. Then I'd use ForEach:

IEnumerable<string> result = list.First();

list.RemoveAt(0);

list.ForEach(delegate(IEnumerable<string> value)
{
     result = (from r in result
               from v in value
               select r + " " + v).ToList();

});

You can also see this link : Cartesian Product for Group members




回答2:


I liked Raeen's answer and it made me think of a simple linq way to solve this problem. This is a very similar method, but doesn't involve any state external to the computation.

var list = new List<IEnumerable<string>>()
{
    new[] {"red", "blue", "orange"},
    new[] {"5 inche", "8 inch"},
    new[] {"x", "y"},
};

var result =
    list
        .Aggregate((rs, vs) =>
            from r in rs
            from v in vs
            select r + " " + v)
        .ToList();


来源:https://stackoverflow.com/questions/26965507/n-ary-multiple-list-cartesian-product

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!