2017-03-06 328 views
1

我有一個列表Dictionary<string, object>。 如何按值查找所有字典中的重複值?如何在List <Dictionary <string,object >>中查找重複值?

+2

的可能的複製[C#:從字典中刪除重複值(http://stackoverflow.com/questions/1462101/c -remove-duplicate-values-from-dictionary) –

+0

posible duplicate of http://stackoverflow.com/questions/7172394/finding-duplicate-values-in-dictionary-and-print-key-of-the-duplicate-element –

+1

他要求在「字典」的「列表」中查找重複項。這些不是完全重複的。 –

回答

1

緊湊代碼使用LINQ:

 List<Dictionary<string, object>> list = new List<Dictionary<string, object>>(); 
     list.SelectMany(dictionary => dictionary.Values).GroupBy(d => d).Where(x => x.Count() >1); 
+1

這隻適用於一本字典。但沒有列表。 – Sebi

+0

看起來像他編輯它 - 檢查出來 –

1

經典老循環

var uniqueValues = new HashSet<object>(); 
var duplicateValues = new List<object>(); 
foreach (var value in yourDictionaries.SelectMany(dict => dict.Values)) 
{ 
    if (uniqueValues.Add(value) == false) 
    { 
     duplicateValues.Add(value); 
    } 
} 

SelectMany是獲取所有詞典的所有值的重要手段。

如果你是LINQ的球迷則可以通過使用AggregateGroupBy

1

你可以找到使用LINQ它們的出現重複值,將其轉換成LINQ表達式的例子。 它給你重複的值和它的出現(列表中的索引和字典中的鍵)。

var duplicates = dicList 
    .SelectMany((x, i) => x.Select(p => new { Index = i, Key = p.Key, Value = p.Value })) 
    .GroupBy(x => x.Value) 
    .Where(x => x.Count() > 1) 
    .Select(x => new 
     { 
      Value = x.First().Value, 
      Occurrences = x.Select(o => new { Index = o.Index, Key = o.Key }) 
     }); 

如果你只是想重複的值,則使用簡化版

var duplicates = listOfDic 
    .SelectMany(x => x.Values) 
    .GroupBy(x => x) 
    .Where(x => x.Count() > 1); 
相關問題