使用Linq获取包含相同关键字的嵌套字典的所有值
本文关键字:嵌套 字典 关键字 Linq 获取 包含相 使用 | 更新日期: 2023-09-27 18:21:27
我仍在努力掌握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"answers"test2-1"。
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"