在C#中循环字典

Jas*_*Cav 3 c# collections dictionary

我意识到你不能在C#中迭代一个Dictionary并编辑底层的Dictionary,如下例所示:

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;
}
Run Code Online (Sandbox Code Playgroud)

我看到解决这个问题的一种方法是使List的键支持List,如下所示:

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;
}
Run Code Online (Sandbox Code Playgroud)

因为我不是自己编辑密钥,所以有任何理由不应该这样做,或者选择这个作为解决方案是不好的.(我意识到如果我正在编辑这些键,这可能会导致很多问题.)

谢谢.

编辑:修复了我的代码示例.对于那个很抱歉.

ibu*_*kov 9

您可以使用KeyValuePair类循环遍历字典.

Dictionary<string, string> d1 = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> val in d1)
{ 
    ...
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*ack 7

在你的例子中,它不像我在编辑字典值(或键)那样?

一般来说,你的解决方案看起来很好,你可以用这样的代码少做一些代码:

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];
   }
}
Run Code Online (Sandbox Code Playgroud)