如何修改关键在C#中的字典字典、关键

2023-09-02 02:09:51 作者:倒数こ3.2.1.

我怎样才能改变在字典中的数字键的值。

How can I change the value of a number of keys in a dictionary.

我有以下词典:

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

我要遍历这个排序的字典和改变的关键,键+ 1,如果关键值大于一定的数量。

I want to loop through this sorted dictionary and change the key to key+1 if the key value is greater than a certain amount.

推荐答案

正如杰森说,你不能改变现有的字典条目的关键。你必须删除/添加使用像这样一个新的密钥:

As Jason said, you can't change the key of an existing dictionary entry. You'll have to remove/add using a new key like so:

// 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);
}