将内部词典更新为外部词典中的值

时间:2012-07-16 12:38:47

标签: c# collections .net-4.0 dictionary foreach

在这样的结构中:

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
}

怎么做?

3 个答案:

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