C#中词典的排列

时间:2015-03-12 03:41:39

标签: c# dictionary combinations permutation

我有一个充满键和值的词典。我试图获得所有可能的密钥组合,没有重复。所以AB和BC和CDE但不是BA。这个值在这个时候并不重要,以后我会利用它们。我该怎么做呢?

Dictionary<string, int> datadict = new Dictionary<string, int>();

datadict.Add("A", 310);
datadict.Add("B", 200);
datadict.Add("C", 510);
datadict.Add("D", 340);
datadict.Add("E", 230);
datadict.Add("F", 940);
datadict.Add("G", 470);
datadict.Add("H", 430);
datadict.Add("I", 440);
datadict.Add("J", 360);

1 个答案:

答案 0 :(得分:1)

某些LINQfor-loops

可能会有效

使用array

将密钥集提取为LINQ
var KeyList = datadict.Select(r => r.Key).ToArray();

示例程序:2个字符的组合

// Keys are extracted from Dictionary : A String Array
var KeyList = datadict.Select(r => r.Key).ToArray();
// Values are extracted from Dictionary : An int Array
var ValueList = datadict.Select(r => r.Value).ToArray();

// Here I have provided a simple algorithm to get Combinations of Two characters
// Ex : AB , AC ... 
// Does not get AA. BB .. OR BA, CA..

int res=0;
// Outer Loop walk through all elements
for (int i = 0; i < KeyList.Length; i++)
{
     // Inner loop walk from outer loop index +1 
     for (int j = i+1; j < KeyList.Length; j++)
     {
          // Find the SUM 
          res=ValueList[i]+ValueList[j];

          // Permutations and the SUM
          Console.WriteLine(KeyList[i]+KeyList[j]+"  "+res);
     }
}

输出:

AB
AC
AD
.
.
IJ