如何从C#中的4x4数组中获取所有可能的对?

时间:2016-08-27 13:22:56

标签: c# arrays

我们说我有一个2x2阵列。

[1, 2]
[3, 4]

我想让所有对都成为可能。

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

我不希望像[2, 1]这样的反对对。

有没有人能解决这个问题呢?

1 个答案:

答案 0 :(得分:2)

您实际上需要三个嵌套循环,或者将您的2d列表转换为1d列表然后获取排列

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