Looping Over Dictionary in C #

I understand that you cannot iterate over a dictionary in C # and edit the basic 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;
}

As I understand it, this is to make a list supported by the dictionary keys, for example:

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;
}

Since I do not edit the keys themselves, is there a reason why this should not be done, or that it is bad to choose this as a solution. (I understand that if I edited these keys, it could cause a lot of problems.)

Thanks.

Edit: Fixed my sample code. Sorry.

+3
source share
4 answers

in your examples, doesn't it seem to me that you're editing dictionary values ​​(or keys)?

, , , :

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];
   }
}
+7

KeyValuePair.

Dictionary<string, string> d1 = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> val in d1)
{ 
    ...
}
+9

Your first part of the code looks good to me - you don't edit the dictionary at all.

+1
source

Here is another version of LINQ-esque:

totalCost = totalCost
     .ToDictionary( kvp => kvp.Key, 5 );

Or if 5 is not quite what you want :)

totalCost = totalCost
     .ToDictionary( kvp => kvp.Key, CalculateSomething(kvp.Value) );

(Note: this does not edit the basic dictionary, instead it replaces it with a new one)

0
source

Source: https://habr.com/ru/post/1712215/


All Articles