How To Build All Possible Combinations Of A List Of Values?

In this article, I will explain how to generate all the possible arranged combinations using the C# code. For Example, an item has 3 options, like size, color, and fabric type using which product is manufactured. Now using the below code, we can find all the possible combinations for all the options used for the item to make a single product with different options.

Code:

Here, I have created a simple C# console application to generate all the possible combinations for the product.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CreateCombinations
{
    class Program
    {
        public static List<string[]> productOptions = new List<string[]> {
            new string[] {
                "XS",
                "S",
                "L"
            },
            new string[] {
                "Black",
                "White",
                "Blue",
                "Green"
            },
            new string[] {
                "Polyster",
                "Cotton"
            }
        };
        static void Main(string[] args)
        {
            GeneratePossibleCombination(0, new List<string>());
            Console.ReadLine();
        }
        public static void GeneratePossibleCombination(int l, List<string> output)
        {
            if (l < productOptions.Count)
            {
                foreach (string value in productOptions[l])
                {
                    List<string> resultList = new List<string>();
                    resultList.AddRange(output);
                    resultList.Add(value);
                    if (resultList.Count == productOptions.Count)
                    {
                        Console.WriteLine(string.Join(", ", resultList));
                        Console.WriteLine("---------------------------");
                    }
                    GeneratePossibleCombination(l + 1, resultList);
                }
            }
        }
    }
}

Output:

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories