Dictionary Iteration
October 2nd, 2009
No comments
In a project I’m working on I am storing results in a dictionary. While I could just be storing them in a list I thought the speed and ease of use was better for a dictionary. [In fact it turned out to be a great choice because due to collisions in the results I discovered that the data was actually bad and needed to be cleaned up.]
Once I had the results through I needed loop through them to export them to a better file format. At first I wasn’t exactly sure how to do this. I new a dictionary implemented the IEnumerable interface I just didn’t know how to access it.
Here is how:
var dictionary as new Dictionary(); dictionary.Add(obj1.GetHashCode(), obj1); dictionary.Add(obj2.GetHashCode(), obj2); dictionary.Add(obj3.GetHashCode(), obj3); foreach (KeyValuePair result in dictionary) { Console.WriteLine(String.Format("Key = {0} - Value = {1}", result.Key, result.Value.ToString()); }