在C#中循环字典

时间:2009-07-09 16:19:56

标签: c# collections dictionary

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

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

我看到解决此问题的一种方法是使用Dictionary的键支持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;
}

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

谢谢。

修改:修复了我的代码示例。对不起。

4 个答案:

答案 0 :(得分:9)

您可以使用KeyValuePair类循环遍历词典。

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

答案 1 :(得分: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];
   }
}

答案 2 :(得分:1)

你的第一段代码看起来很好 - 你根本就没有编辑字典。

答案 3 :(得分:0)

这是另一个LINQ-esque版本:

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

或者,如果5不是你想要的那样:)

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

(注意:这不会编辑基础词典,而是用新词替换它)