简体   繁体   English

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

[英]How to modify key in a dictionary in C#

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。

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

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)中的键,键必须是不可变的。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM