I have a List of Dictionary<string, object>
.
How to find duplicate values in all dictionaries by value?
Asked
Active
Viewed 3,764 times
1

Hamid Pourjam
- 20,441
- 9
- 58
- 74

ruslanen
- 69
- 2
- 11
-
2Possible duplicate of [C#: Remove duplicate values from dictionary?](http://stackoverflow.com/questions/1462101/c-remove-duplicate-values-from-dictionary) – Tadija Bagarić Mar 06 '17 at 06:49
-
posible duplicate of http://stackoverflow.com/questions/7172394/finding-duplicate-values-in-dictionary-and-print-key-of-the-duplicate-element – Axel Bouttelgier Mar 06 '17 at 06:49
-
1He's asking for finding duplicates in a `List` of `Dictionaries`. Those aren't exact duplicates. – Ilian Mar 06 '17 at 06:52
-
Duplicates within a dictionary or any duplicate value? – Hamid Pourjam Mar 06 '17 at 06:55
-
doctor, duplicates in List of dictionaries. – ruslanen Mar 06 '17 at 07:09
-
Thanks guys! That helped. – ruslanen Mar 07 '17 at 06:17
3 Answers
2
You can find duplicate values with their occurrences using LINQ. It gives you duplicate values and its occurrences (index in list and key in dictionary).
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 })
});
If you just want duplicate values then use simplified version
var duplicates = listOfDic
.SelectMany(x => x.Values)
.GroupBy(x => x)
.Where(x => x.Count() > 1);

Hamid Pourjam
- 20,441
- 9
- 58
- 74
1
Use linq for compact code:
List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
list.SelectMany(dictionary => dictionary.Values).GroupBy(d => d).Where(x => x.Count() >1);

Murad
- 523
- 4
- 17
1
Old classic loop
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
is a key method for getting all values of all dictionaries.
If you are fan of LINQ you can convert it to the LINQ expression for example by using Aggregate
or GroupBy

Fabio
- 31,528
- 4
- 33
- 72