Build All Possible Combinations Of A List Of Values

In this blog, I will demonstrate how to generate possible permutations and combinations using C# console application. Let's take an example of a product that has few options, like size, color, material used to make the product. When we want to find all possible combinations for each options used for product to make single product with different option available,

Let's create product option list with all option values,

public static List < string[] > productOptions = new List < string[] > {
    new string[] {
        "Large",
        "Medium",
        "Small"
    },
    new string[] {
        "Black",
        "Blue",
        "Soft Pink",
        "Purple"
    },
    new string[] {
        "Polyster",
        "Cotton"
    }
};

Now will create recursive function which will build possible combinations for us,

public static void BuildPossibleCombination(int level, List < string > output) {
    if (level < productOptions.Count) {
        foreach(string value in productOptions[level]) {
            List < string > resultList = new List < string > ();
            resultList.AddRange(output);
            resultList.Add(value);
            if (resultList.Count == productOptions.Count) {
                Console.WriteLine(string.Join(", ", resultList));
                Console.WriteLine("-------------------");
            }
            BuildPossibleCombination(level + 1, resultList);
        }
    }
}

Let's call this function from our main method,

static void Main(string[] args) {
    BuildPossibleCombination(0, new List < string > ());
    Console.ReadLine();
}

The final output will look as below with all combinations.

Build All Possible Combinations Of A List Of Values