在字典内迭代字典

时间:2019-08-28 11:38:46

标签: c# linq

我试图遍历字典Dictionary<uint,Dictionary<uint,uint>> myDict

我想更改内部字典的值。

当我使用时:

foreach(var item in myDict)
{
    foreach(var rt in item)

我得到了错误:

  

严重性代码描述项目文件行抑制状态   错误CS1579 foreach语句无法对类型为变量的变量进行操作   'KeyValuePair >'因为   'KeyValuePair >'不包含公共   GetEnumerator'SparrowView的实例定义

我为什么不能在里面枚举?

3 个答案:

答案 0 :(得分:5)

请尝试使用 AXP CSCO HD PG Date 2019-06-20 124.530563 57.049965 211.250000 111.021019 2019-06-21 124.341156 56.672348 209.389999 110.484497 2019-06-24 123.752991 56.821407 205.500000 111.607231 2019-06-25 122.776054 55.728306 204.740005 111.001152 2019-06-26 123.204704 56.245041 206.419998 109.023956

由于您当前正在遍历uint和字典,而不仅是字典。

答案 1 :(得分:4)

在迭代中使用foreach的方式会得到KeyValuePair,它不能被迭代为错误状态。

因此,您需要外部foreach内部的值,该值可以是您可以迭代的Dictionary,如下所示:

foreach(var item in myDict)
{
    foreach(var rt in item.Value)
    {
        ...
    }
}

此外,您可以使用myDict.SelectMany(kvp => kvp.Value).ToArray();来返回包含所有字典中所有键和值对的数组,然后可以一次遍历所有字典(无嵌套循环)。

答案 2 :(得分:1)

如果您要在内部字典中查找特定的键,那么对键集合进行浏览并按键寻址字典可能更有意义:

foreach(var outerKey in myDict.Keys)
{
   foreach(var innerKey in myDict[outerKey].Keys)
   {
     if(innerKey == 3)
       ...
   }
}

或者,如果直接迭代字典,则会得到一个键值对,因此必须牢记键(uint)和值(外层的字典,内层的uint)之间的区别< / p>

foreach(var outerKvp in myDict) //foreaching the outer dictionary gives a keyvaluepair, the value of which is a dictionary
{
   foreach(var innerKvp in outerKvp.Value) //outerKvp.Value is a Dictionary<uint,uint), foreaching it will again give you a keyvaluepair, this time for the inner dictionary. the value this time is a uint
   {
     if(innerKvp.Key == 3)
       ...
   }
}

还请记住,如果您想修改其中的任何一个,您都不能在for循环内完成,因为您无法修改您要枚举的字典。在这种情况下,最好只使用ContainsKey:

//for example if you know the outer key
if(myDict.ContainsKey(1) && myDict[1].ContainsKey(3))
    myDict[1][3] = 4;

//or if you don't know the outer key
foreach(var outerKey in myDict.Keys)
{
   if(myDict[outerKey].ContainsKey(3))
       myDict[outerKey][3] = 4; //this will succeed because we aren't enumerating the inner dict
}

请仔细考虑这是否是满足您需求的最佳数据存储容器;拥有字典的字典有点麻烦,您可能会更好地用uint制作复合键,并使用单个字典或一起选择另一个数据存储容器