在这样的结构中:
Dictionary<myObject, Dictionary<myEnum, secondObject>> myDict;
我使用foreach
搜索外Dictionary
中的所有项目:
foreach (var elem in myDict)
{
//I need to make some modifications in inner Dictionary for chosen myEnum
}
怎么做?
答案 0 :(得分:2)
foreach
上的Dictionary
循环枚举键值对。关键在于elem.Key
;值(即您的目标内部字典)为elem.Value
。
foreach (var elem in myDict)
{
//I need to make some modifications in inner Dictionary for chosen myEnum
Dictionary<myEnum, secondObject> inner = elem.Value;
inner[myEnum.EnumVal1] = new secondObject(123);
inner[myEnum.EnumVal2] = new secondObject(456);
}
答案 1 :(得分:1)
你很亲密,似乎你对访问内部字典感到困惑吗?
foreach (var elem in myDict) // var is KeyValuePair<myObject, Dictionary<myEnum, secondObject>>
{
var innerDict = elem.Value; // Value is Dictionary<myEnum, secondObject>
if (innerDict != null)
{
if (innerDict.ContainsKey(enumVal)) // key is myEnum
{
var value = innerDict[enumVal]; // var is secondObject
}
}
}
答案 2 :(得分:0)
由于没有给出关于myObject或secondObject的详细信息,以下内容可能过于通用,但至少可能会给你一个想法:
foreach (var elem in myDict)
{
var temp = elem.Value.Single(p => p.Key == MyEnum.a);
(temp.Value as MySecondObject).anyProperty = anyValue;
}