1

我仍在尝试掌握 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”。

4

1 回答 1

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"
于 2013-07-05T20:53:01.390 回答