Home > Software engineering >  How to build all combinations of few list or arrays
How to build all combinations of few list or arrays

Time:01-21

I didnt wrote any code yet as I dunno how to even start it,

I have few lists:

List<string> list1 = { A1, B1, C1 }
List<string> list2 = { A2, B2 }
List<string> list3 = { A3, B3, C3 }

and I want to build each possible variations by taking one element from each list and build unique list. Looking for way to find all variation.

Let's say we foreach element in list1 we take 1 element from list2 and 1 element from list.

So first variation for list1[0]:

A1, A2, A3
A1, A2, B3
A1, A2, C3

A1, B2, A3
A1, B2, B3
A1, B2, C3

I want build all variations of strings and save as separated line in list file. My head cant crawl it how I can code the logic.

CodePudding user response:

you can use the SelectManyof LINQ to get the desired output.

List<string> list1 = new List<string>{ "text1", "text2", "text3" };
List<string> list2 = new List<string> { "text4", "text5", "text6" };
List<string> list3 = new List<string> { "text7", "text8", "text9" };

var allCombinations = list1.SelectMany(x => list2, (x, y) => x   " "   y)
                            .SelectMany(x => list3, (x, z) => x   " "   z)
                            .ToList();

my code is based on the data, you provided earlier.

I would suggest you read about SelectMany

  • Related