Home > Software engineering >  Replacing a Dictionary Value without CS0200
Replacing a Dictionary Value without CS0200

Time:11-03

I have the following code, which is iterating through a JSON file where I need to replace all values with a specific character. Note that translationDictionary is of the following type, because I do not know any of the keys at compile time:

Dictionary<string, Dictionary<string, string>>?

In this case I'm just replacing them with "*":

foreach (var key in translationDictionary)
{
    foreach (var entry in key.Value)
    {
        var replaceString = new string("*".ToCharArray()[0], entry.Value.Length);
        key.Value = replaceString;
    }
}

This gives me a CS0200 error because the property is read-only.

CS0200

I have tried some form of creating a totally new entry and swapping it out, but I'm not sure if it's the correct approach. I am also running into trouble because it's currently being used as the iteration variable:

var newEntry = new KeyValuePair<string, string>(entry.Key, replaceString);

How can I properly modify this code such that the entry's values are replaced with my replaceString variable?

CodePudding user response:

If you need to modify dictionary entry - use dictionary indexer: someDict[key] = newValue. In your case that would be:

foreach (var key in translationDictionary) {
    foreach (var entry in key.Value) {
        // no need to do "*".ToCharArray()[0] by the way
        key.Value[entry.Key] = new string('*', entry.Value.Length);
    }
}
  •  Tags:  
  • c#
  • Related