Djeurissen Djeurissen - 3 months ago 8
C# Question

How to get all possible pairs from an 4x4 Array in C#?

Lets say I have an 2x2 Array.

[1, 2]
[3, 4]


And I want to get all pairs possible.

[1, 2] [1, 3] [1, 4] [2, 3] [2, 4] [3, 4]


And I do not want reversed pairs like
[2, 1]
.

Has anyone a good solution for this problem?

Answer

You will actually need three nested loops, or to convert your 2d list to 1d list and then to get your Permutations:

List<List<int>> My2DList = new List<List<int>>() { new List<int>(){ 1, 2 }, new List<int>(){ 3, 4 } }; // your initial 2d list
List<int> My1DList = My2DList.Cast<int>().ToList(); // convert to 1d list
List<List<int>> Permutations = new List<List<int>>(); // prepare a container

for (int i = 0; i < My1DList.Count; i++)
    for(int j = i; j < My1DList.Count; j++)
        Permutations.Add(new List<int>() { My1DList[i], My1DList[j] }); // add your permutations