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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1937847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:01:17  来源:igfitidea点击:

How to modify key in a dictionary in C#

c#.netdictionarykey

提问by Bernard Larouche

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

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

I have the following dictionary :

我有以下字典:

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

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.

如果键值大于一定数量,我想遍历这个排序的字典并将键更改为键+1。

采纳答案by Dan Tao

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

回答by jason

You need to remove the items and re-add them with their new key. Per MSDN:

您需要删除项目并使用新密钥重新添加它们。每MSDN

Keys must be immutable as long as they are used as keys in the SortedDictionary(TKey, TValue).

键必须是不可变的,只要它们在SortedDictionary(TKey, TValue).

回答by goofballLogic

If you don't mind recreating the dictionary, you could use a LINQ statment.

如果您不介意重新创建字典,则可以使用 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); 

or

或者

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

回答by marcel

You can use LINQ statment for it

您可以使用 LINQ 语句

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