如何修改关键在C#中的字典 [英] How to modify key in a dictionary in C#

查看:208
本文介绍了如何修改关键在C#中的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于如何修改关键在C#中的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆