Search code examples
c#sortedlist

Sortedlist/Dictionary modify a key's value at an index


So what i want to do is this:

SortedList<char, int> list = new SortedList<char, int>()
 {
    {'a', 31312},
    {'b', 42224},
    {'c', 42342},
};

for (int i = 0; i < list.Count; i++)
{
      dict.Values[i] = i;
}

But it is not possible, when i try it give

This operation is not supported on SortedList nested types because they require modifying the original SortedList

It is just an example code, so i need a dictionary/sortedlist or somehwat suitable and later i want to modify the values at a specific index like what i did in the for.

Any suggestion?


Solution

    1. You have defined SortedList named list, but then call dict
    2. Index type is char and You are using int (int i)

    You can change SortedDictionary values as shown below:

    var dict = new SortedDictionary<char, int>()
    {
        {'a', 31312},
        {'b', 42224},
        {'c', 42342},
    };
    
    for (char c = 'a'; c <= 'c'; ++c)
    {
        dict[c] = (int)c;
    }