我有一个与组合有关的问题.
I am actually developing a ecommerce site and I have a function to allow customer create product variant.
For example: Black Pant 34W 30L, Black Pant 38W 32L, White Pant 34W 30l. Those are defined as product variants.
Assume my pant has 3 options, and they are color, waist size and length.
I now have 3 list.
ListA = {"black", "white", "red"} //For the color
ListB = {30,32,34,36,38} //For the waist
ListC ={28,30,32,34} //For the length
Run Code Online (Sandbox Code Playgroud)
My question is how can I list all the possible combinations?
My desired result should be look like {{black,30,28},{black,30,30},{black,30,32},{white,34 ,30}}
P.S. The tricky part is that I don't know how many options customer will assign to this product. The count of the option might be just 1, which is the easiest; it could be more than 3...
Problem Solved
Since we don't know how many options we will have. Therefore, we don't know how many for loop we are going to use. In other word, it turns to a typical Cartesian Products.
For more information, you can read from these two links. http://www.interact-sw.co.uk/iangblog/2010/07/28/linq-cartesian-1 http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx
Thank you for all your help!
正如评论中所述,Eric Lippert有一篇名为" 计算笛卡尔积与LINQ"的博客文章,解释了如何解决您的问题.您需要一种扩展方法来计算笛卡尔积:
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {
IEnumerable<IEnumerable<T>> result = new [] { Enumerable.Empty<T>() };
foreach (var sequence in sequences) {
var localSequence = sequence;
result = result.SelectMany(
_ => localSequence,
(seq, item) => seq.Concat(new[] { item })
);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
然后,您需要一系列序列来执行产品.你的情况,你有两个字符串和整数在你的序列从而使公共基类型T必须是Object.
var sequences = new[] {
new Object[] { "black", "white", "red" },
new Object[] { 30, 32, 34, 36, 38 },
new Object[] { 28, 30, 32, 34 }
};
Run Code Online (Sandbox Code Playgroud)
要计算笛卡尔积,只需调用扩展方法:
var result = sequences.CartesianProduct();
Run Code Online (Sandbox Code Playgroud)
当你枚举结果时,它会在运行中计算(懒惰).如果您希望创建一个列表列表,则需要在从扩展方法返回ToList()之后调用.Concatresult