Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing a Dictionary Value without CS0200

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 "*":

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading