2011-10-13 61 views
0

我有任意數量的字典(在列表中,已經按順序),我希望外連接。例如,對於Ñ = 2:如何將具有唯一鍵的字典列表轉換爲值爲列表的字典?

List<Dictionary<string, int>> lstInput = new List<Dictionary<string, int>>(); 
Dictionary<string, int> dctTest1 = new Dictionary<string, int>(); 
Dictionary<string, int> dctTest2 = new Dictionary<string, int>(); 
dctTest1.Add("ABC", 123); 
dctTest2.Add("ABC", 321); 
dctTest2.Add("CBA", 321); 
lstInput.Add(dctTest1); 
lstInput.Add(dctTest2); 

每個字典已經具有唯一鍵。

我想變換lstInput爲:

Dictionary<string, int[]> dctOutput = new Dictionary<string, int[]>(); 

其中dctOutput樣子:

"ABC": [123, 321] 
"CBA": [0, 321] 

也就是說,一套dctOutput鍵是等於設定的鍵聯盟每個字典lstInput;此外,如果沒有對應的密鑰,則dctOutput中每個值的第* i * th個位置等於第或第0位置的* i * th字典中相應密鑰的值。

如何編寫C#代碼來完成此操作?

回答

0

以下應該做你想要的。

var dctOutput = new Dictionary<string, int[]>(); 
for (int i = 0; i < lstInput.Count; ++i) 
{ 
    var dict = lstInput[i]; 
    foreach (var kvp in dict) 
    { 
     int[] values; 
     if (!dctOutput.TryGetValue(kvp.Key, out values)) 
     { 
      // Allocating the array zeros the values 
      values = new int[lstInput.Count]; 
      dctOutput.Add(kvp.Key, values); 
     } 
     values[i] = kvp.Value; 
    } 
} 

這工作,因爲分配的數組初始化所有數值爲0。因此,如果以前的字典沒有與該鍵的項目,它的值將在該位置0。如果你想讓你的標記值不是0,那麼你可以在分配數組後使用該值初始化數組。

相關問題