在这样的构造中:
Dictionary<myObject, Dictionary<myEnum, secondObject>> myDict;
我foreach
用来搜索 external 中的所有项目Dictionary
:
foreach (var elem in myDict)
{
//I need to make some modifications in inner Dictionary for chosen myEnum
}
这个怎么做?
在这样的构造中:
Dictionary<myObject, Dictionary<myEnum, secondObject>> myDict;
我foreach
用来搜索 external 中的所有项目Dictionary
:
foreach (var elem in myDict)
{
//I need to make some modifications in inner Dictionary for chosen myEnum
}
这个怎么做?
a 上的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);
}
你很亲密,看来你只是对访问内部字典有些困惑?
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
}
}
}
由于没有提供有关 myObject 或 secondObject 的详细信息,因此以下内容可能过于笼统,但至少可以给您一个想法:
foreach (var elem in myDict)
{
var temp = elem.Value.Single(p => p.Key == MyEnum.a);
(temp.Value as MySecondObject).anyProperty = anyValue;
}