Home > Net >  How can I subtract a number from a value in a C# dictionary
How can I subtract a number from a value in a C# dictionary

Time:12-03

I need to subtract 1 from the value of a Dictionary<string, int> as the int contains the numbers of a lot that need to be decreased when a foreach is entered, but I don't seem to find a solution.

foreach(KeyValuePair<string, int> i in myDictionary)

i.Value -= 1;

The above is not possible, if I try to do myDictionary[i] -= 1 I still get errors. Any suggestion?

CodePudding user response:

Your dictionary is indexed by a key of type string here. So you can do something like this:

myDictionary["some value"] -= 1;

If you wanted to subtract 1 from every value then you could do it like this:

foreach (var key in myDictionary.Keys) 
{
    myDictionary[key] -= 1;
}

Example: https://dotnetfiddle.net/L9CV0B

CodePudding user response:

You can't change a value of keyvaluepair since it read only. Try this code. it was tested in visual studio

  1. you can replace with new keyvaluepairs
dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value -1);
  1. or just change value
 for (int i = 0; i < myDictionary.Count; i  )
 {
        string key = dict.Keys.ElementAt(i);
        dict[key]-=1;
  }
  • Related