关于.net:如何在C#中修改字典中的键

How to modify key in a dictionary in C#

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

我有以下字典:

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

如果键值大于某个值,我想循环浏览这个经过排序的字典,并将键值更改为key+1。


正如Jason所说,您不能更改现有字典条目的键。您必须使用如下新键删除/添加:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 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);
}


您需要删除这些项,并用它们的新键重新添加它们。根据msdn:

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


你可以用LINQ标签

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


如果您不介意重新创建字典,可以使用LINQ语句。

1
2
3
4
5
6
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);

1
2
3
4
5
6
7
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);