2015-12-21 27 views

回答

0

以下是你需要做的:

var result = list 
    .SelectMany(l => l.Keys) 
    .Distinct() 
    .Where(k => list.All(l => l.ContainsKey(k))) 
    .ToList(); 

,或建立在@ ken2k解決方案(可能會有更好的性能):

var duplicatedKeys = myList 
    .SelectMany(z => z.Keys) 
    .GroupBy(z => z) 
    .Where(z => z.Count() == myList.Count) //Number of items in group should be equal to the number of dictionaries in the list 
    .Select(z => z.Key) 
    .ToList(); 
+0

謝謝!)這是工作) –

6

一個GroupBy應該足以隔離包含多個元素的鍵組:

var duplicatedKeys = myList 
    .SelectMany(z => z.Keys) // Flattens the keys to a unique IEnumerable 
    .GroupBy(z => z)   // Group keys by key 
    .Where(z => z.Count() > 1) // Get groups with more than 1 occurence 
    .Select(z => z.Key)   // Get the actual key 
    .ToList(); 
+0

這就像是一樣var duplicatedKeys = myList .SelectMany(z => z.Keys).Distinct(); 我得到所有字典中的所有密鑰。 我只需要獲得在所有字典中重複的鍵。 –

+0

該解決方案將返回兩個或更多詞典中存在的鍵。 OP希望獲得* all *字典中存在的密鑰。 –

+2

@YacoubMassad在發佈這個答案後,OP的問題被修改了。最初的例子說'aaa1'應該被退回,但它並沒有出現在所有字典中。 – ken2k

3
var set = new HashSet<string>(); 
var duplicates = list 
        .SelectMany(x => x.Keys) 
        .Where(x => !set.Add(x)); 
+1

最好是添加一些評論,而不是僅僅在那裏扔代碼。 –

相關問題