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

Ber*_*che 43 .net c# dictionary key

如何更改字典中多个键的值.

我有以下字典:

SortedDictionary<int,SortedDictionary<string,List<string>>>
Run Code Online (Sandbox Code Playgroud)

如果键值大于某个量,我想循环遍历此排序字典并将键更改为键+ 1.

Dan*_*Tao 42

正如杰森所说,你无法改变现有词典条目的关键.您必须使用新密钥删除/添加,如下所示:

// 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);
}
Run Code Online (Sandbox Code Playgroud)


jas*_*son 22

您需要删除这些项目并使用新密钥重新添加它们.每个MSDN:

键必须是不可变的,只要它们被用作键中的键SortedDictionary(TKey, TValue).


mar*_*cel 5

您可以使用 LINQ 语句来实现它

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