List all possible combinations

I have a question related to the combination.

I am actually engaged in the development of an e-commerce site, and I have a feature that allows the client to create a product.

For example: Black Pant 34W 30L, Black Pant 38W 32L, White Pant 34W 30l. They are defined as product options.

Suppose my pants have 3 options, and they are color, size and waist length.

Now I have 3 lists.

ListA = {"black", "white", "red"} //For the color ListB = {30,32,34,36,38} //For the waist ListC ={28,30,32,34} //For the length 

My question is, how can I list all possible combinations?

My desired result should look like {{black, 30,28}, {black, 30,30}, {black, 30,32}, {white, 34, 30}}

PS The hard part is that I don’t know how many options the client will assign to this product. The counter can be only 1, which is the simplest; it can be more than 3 ...

Problem resolved

Since we do not know how many options we will have. Therefore, we do not know how many cycles we will use. In other words, he refers to typical Cartesian works.

For more information, you can read 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 your help!

+2
source share
1 answer

As pointed out in the comments, Eric Lippert has a blog post called Computing a Cartesian product with LINQ that explains how to solve your problem. You need an extension method to calculate the Cartesian product:

 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; } 

Then you need a sequence of sequences to complete the product. In your case, you have integers and integers in your sequences, so the common base type T should be Object .

 var sequences = new[] { new Object[] { "black", "white", "red" }, new Object[] { 30, 32, 34, 36, 38 }, new Object[] { 28, 30, 32, 34 } }; 

To calculate the Cartesian product, you simply call the extension method:

 var result = sequences.CartesianProduct(); 

When you list the result, it is calculated "on the fly" (lazily). If you prefer to create a list of lists, you need to call ToList() after Concat , as well as before returning the result from the extension method.

+4
source

Source: https://habr.com/ru/post/974083/


All Articles