2009-12-21 56 views
35

如何更改字典中多個鍵的值。如何修改C#中的字典中的密鑰

我有以下的解釋:

SortedDictionary<int,SortedDictionary<string,List<string>>> 

我想遍歷這個排序的字典和改變的關鍵,鍵+ 1,如果鍵值是超過一定數額更大。

+7

爲什麼這個否決? – keyboardP 2009-12-21 02:23:19

+4

您無法修改密鑰。相反,刪除鍵併爲鍵+ 1添加一個新值。 – 2009-12-21 02:29:39

+1

這個問題聽起來像是您嘗試手動插入一個項目並對其進行排序(具體而言,爲一個項目騰出空間)。注意SortedDictionary已經爲你做了這個。 – Russell 2009-12-21 02:30:41

回答

34

正如Jason所說,您無法更改現有字典條目的密鑰。您必須使用如下新鍵來移除/添加:

// we need to cache the keys to update since we can't 
// modify the collection during enumeration 
var keysToUpdate = new List<int>(); 

foreach (var entry in dict) 
{ 
    if (entry.Key < MinKeyValue) 
    { 
     keysToUpdate.Add(entry.Key); 
    } 
} 

foreach (int keyToUpdate in keysToUpdate) 
{ 
    SortedDictionary<string, List<string>> value = dict[keyToUpdate]; 

    int newKey = keyToUpdate + 1; 

    // increment the key until arriving at one that doesn't already exist 
    while (dict.ContainsKey(newKey)) 
    { 
     newKey++; 
    } 

    dict.Remove(keyToUpdate); 
    dict.Add(newKey, value); 
} 
+0

我想你可能會遇到一個帶有keyToUpdate的OutOfBoundsException +1 – 2009-12-21 02:39:44

+0

爲什麼會發生這種情況? – 2009-12-21 02:40:46

+0

非常感謝Dan 這就是我正在尋找的。 – 2009-12-21 03:13:16

20

您需要刪除這些項目並用它們的新密鑰重新添加它們。每MSDN

只要鍵被用作SortedDictionary(TKey, TValue)中的鍵,鍵必須是不可變的。

1

如果您不介意重新創建字典,則可以使用LINQ語句。

var dictionary = new SortedDictionary<int, SortedDictionary<string, List<string>>>(); 
var insertAt = 10; 
var newValues = dictionary.ToDictionary(
    x => x.Key < insertAt ? x.Key : x.Key + 1, 
    x => x.Value); 
return new SortedDictionary<int, SortedDictionary<string, List<string>>>(newValues); 

var dictionary = new SortedDictionary<int, SortedDictionary<string, List<string>>>(); 
var insertAt = 10; 
var newValues = dictionary.ToDictionary(
    x => x.Key < insertAt ? x.Key : x.Key + 1, 
    x => x.Value); 
dictionary.Clear(); 
foreach(var item in newValues) dictionary.Add(item.Key, item.Value); 
+0

不需要創建一個新的爲它創建一個變量。 查看我的評論 – marcel 2015-09-13 17:51:51

1

您可以使用LINQ statment它

var maxValue = 10 
sd= sd.ToDictionary(d => d.key > maxValue ? d.key : d.Key +1, d=> d.Value);