[英]Acquiring all values of nested dictionaries that contain the same key using Linq
我仍在嘗試使用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”。
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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.