+ 2

Accessing values of dictionary not by Key

Imagine we have a dictionary<string , int> and we want to manipulate values of this dictionary. As far as i know, we can access value only by its key. But i think it is inefficient because we must add a couple of line to do that. Is there another solution. For example in array we can access elements and modify them by index. Is there a similar solution to change values in dictionary? Thank you a lot guy.

27th Dec 2020, 2:13 PM
Mohammad Reza Moravejolahkami
Mohammad Reza Moravejolahkami - avatar
7 Answers
+ 3
The solution can be i.e.: foreach (var a in coffee.Keys.ToArray()){ coffee[a]-=discount; Console.WriteLine(coffee[a]); }
27th Dec 2020, 7:25 PM
JaScript
JaScript - avatar
+ 4
What do you see here inefficient: foreach (string s in d.Keys) Console.WriteLine(s + ": " + d[s]); Otherwise you can use generic collections depending of needed application.
27th Dec 2020, 2:32 PM
JaScript
JaScript - avatar
+ 3
Thank you a lot JaScript . The best for you.
27th Dec 2020, 7:37 PM
Mohammad Reza Moravejolahkami
Mohammad Reza Moravejolahkami - avatar
+ 2
What do you mean with var a? Please link your attempt first here then can be seen to help you.
27th Dec 2020, 6:27 PM
JaScript
JaScript - avatar
+ 2
https://code.sololearn.com/cEo3BQKUFuVs/?ref=app Note:i dont want directly use keys of dictionary.
27th Dec 2020, 6:40 PM
Mohammad Reza Moravejolahkami
Mohammad Reza Moravejolahkami - avatar
+ 1
foreach (var a in coffee.Keys){ coffee[a]-=discount; } coffee is a dictionary. The above code results in exception. discount and values of coffee are integer type. JaScript : you mention using generic collection . How can i do the same job using collection?
27th Dec 2020, 3:22 PM
Mohammad Reza Moravejolahkami
Mohammad Reza Moravejolahkami - avatar
+ 1
Mohammad Reza Morawej You are welcome.
27th Dec 2020, 7:40 PM
JaScript
JaScript - avatar