使用Linq获取包含相同键的嵌套字典的所有值

时间:2013-07-05 20:47:31

标签: c# linq dictionary

我仍然试图掌握LINQ,虽然我对更简单的功能有一点了解,但堆叠这些在一定程度上使我望而却步,我希望有人可以帮我一把。

我目前有一本有效的词典:

Dictionary<Type, Dictionary<int, EntityComponent>> ComponentSystems

我正在尝试编写一个方法,它将返回具有给定键的所有EntityComponent实例,也就是说,如果父词典包含两个嵌套词典,并且每个词组都有一个以“1”作为键的条目,该方法将返回与所述键匹配的值IEnumerable<EntityComponent>

我已经使用SelectMany和所有其他各种LINQ命令进行了调整,但我仍然在努力解决这个问题。

作为另一个例子,我要说明我有以下设置:

Dictionary<object, Dictionary<int, string>> test = 
   new Dictionary<object, Dictionary<int, string>>();

Dictionary<int, string> test1 = new Dictionary<int, string>();
test1[1] = "test1-1";
test1[2] = "test1-2";
test[0] = test1;

Dictionary<int, string> test2 = new Dictionary<int, string>();
test2[1] = "test2-1";
test2[2] = "test2-2";
test[1] = test2;

鉴于我要找的密钥是'1',我需要生成一个linq语句,它将同时返回“test1-1”和“test2-1”。

1 个答案:

答案 0 :(得分:2)

int key = 1;
var query = test.Values // select inner dictionaries
                .Where(d => d.ContainsKey(key)) // which contain your key
                .Select(d => d[key]); // and return value by key

返回:

"test1-1"
"test2-1"
相关问题