![](/img/trans.png)
[英]How to get flattened list from dictionary key query where values are lists?
[英]Dictionary of lists to (flattened) List
我有一個<MyKey, List<MyClass>>
類型的字典和一個MyClass
類型的列表。 現在,我要檢查后者中是否有未包含在字典中任何列表中的元素。 我的第一種方法是嵌套兩個循環(一個用於實際列表,一個用於字典中的列表)。 如果找到一個項目,我可以中斷內循環並繼續外循環中的下一個元素。
foreach (MyClass feature in features)
{
bool found = false;
foreach (var kv in this._features) // this._features is the dictionary
{
if (kv.Value.Contains(feature))
{
found = true;
continue;
}
}
if (!found) result.Add(feature);
}
到目前為止,該方法仍然有效,但是我希望使用更短的方法,可能使用LINQ。 我認為如果將字典的值拼合為一個列表可能會起作用,但是我不知道如何實現此目的。
使用SelectMany
將值SelectMany
為IEnumerable<MyClass>
然后使用Except
獲得差異:
var differentElements = this._features.SelectMany(x => x.Value).Except(features);
result.AddRange(differentElements);
如果MyClass
沒有正確覆蓋Equals
和GetHashCode
則可能無法按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.