1

I have a List of Dictionary<string, object>. How to find duplicate values in all dictionaries by value?

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
ruslanen
  • 69
  • 2
  • 11

3 Answers3

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