- Home /
 
               Question by 
               Crystalline · Apr 30, 2015 at 11:43 AM · 
                stringfloatdictionaryiterate  
              
 
              Iterate through String,Float dictionary.
Hi, how do i do this ?
 foreach (string gunStat in attachStats.Keys) 
where attachStats is
 Dictionary<string,float> attachStats
Iterating that way returns me an error...
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by HarshadK · Apr 30, 2015 at 11:47 AM
You can iterate through a Dictionary using:
 foreach(KeyValuePair<string,float> attachStat in attachStats)
 {
     //Now you can access the key and value both separately from this attachStat as:
     Debug.Log(attachStat.Key);
     Debug.Log(attachStat.Value);
 }
This is the preferred way. Another is to use the foreach loop the OP used like this:
 foreach (string key in attachStats.$$anonymous$$eys)
 {
     float val = attachStats[key];
     Debug.Log(key + " = " + val);
 }
This has slightly more overhead since to access each value you have to lookup the key in the dictionary. However since a Dictionary lookup is considered O(1) complexity it might not make a big difference. I would prefer the $$anonymous$$eyValuePair method as it grabs both (key and value) at the same time.
btw: This is a case where i often use the var keyword in C# ^^
 foreach(var attachStat in attachStats)
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                