Looping Over Dictionary in C#

c#, collections, dictionary

Solution

in your examples it doesn't look to me like you're editing the dictionary values (or keys)?

In general your solution looks fine, you could do it with a bit less code like this:

List<double> total = new List<double>();
foreach (AKeyObject key in aDictionary.Keys.ToList())
{
   for (int i = 0; i < aDictionary[key].Count; i++)
   {
      total[i] += aDictionary[key][i];
   }
}

Problem

I realize that you cannot iterate over a Dictionary in C# and edit the underlying Dictionary as in the following example: ``` Dictionary<Resource, double> totalCost = new Dictionary<Resource, double>(); // Populate the Dictionary in here - (not showing code). foreach (Resource resource in totalCost.Keys) { totalCost[resource] = 5; } ``` One way I see to fix this is to make a List backed by the Dictionary's keys, like this: ``` Dictionary<Resource, double> totalCost = new Dictionary<Resource, double>(); // Populate the Dictionary in here - (not showing code). foreach (Resource resource in new List(totalCost.Keys)) { totalCost[resource] = 5; } ``` Because I'm not editing the keys themselves, is there any reason that this should not be done or that it's bad to choose this as a solution. (I realize if I was editing those keys, this could cause a lot of problems.) Thank you. Edit: Fixed my code example. Sorry about that.

Original source