- Home /
How can you iterate through a dictionary and change every value?
I have a dictionary for strings and floatrs,
public Dictionary<string, float> StockNames = new Dictionary<string, float>();
void Start(){
StockNames.Add("ChickenNFries_S", 68.41f);
}
foreach (string v in StockNames.Keys)
{
Debug.Log(v);
}
Then that to iterate through which works. However, you cannot directly change the variable through the iteration as it errors out. I tried to throw another function in there which would be called each iteration
IE changeValue(v)
but that errored as well not allowing me to change them, leaving the only way I know how by literally typing in each name StockNames["ChickenSFries_S"] = 2.0f; Isn't there a way to iterate through them all and set them as you go?
Answer by Glurth · Feb 24, 2016 at 06:04 AM
You can get a collection of all the values (https://msdn.microsoft.com/en-us/library/ekcfxy3x(v=vs.110).aspx), but I dont think that will help with non-reference types like float.
You could get the collection of all keys (https://msdn.microsoft.com/en-us/library/yt2fy5zk(v=vs.110).aspx), then loop through that to get your dictionary indexes. e.g. (uncompiled example)
Dictionary<string, float> StockNames = new Dictionary<string, float>();
//... dic intilization stuff...
Dictionary<string, float>.KeyCollection keys = StockNames.Keys;
foreach (string s in keys)
{
StockNames[s] = 68.234f;
}
Your answer