How to modify key in a dictionary in C#

C#.NetDictionaryKey

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

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

Solution 3 - C#

You can use LINQ statment for it

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

Solution 4 - C#

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBernard LaroucheView Question on Stackoverflow
Solution 1 - C#Dan TaoView Answer on Stackoverflow
Solution 2 - C#jasonView Answer on Stackoverflow
Solution 3 - C#marcelView Answer on Stackoverflow
Solution 4 - C#goofballLogicView Answer on Stackoverflow