1

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

6
  • 2
    Possible duplicate of C#: Remove duplicate values from dictionary? Commented Mar 6, 2017 at 6:49
  • posible duplicate of stackoverflow.com/questions/7172394/… Commented Mar 6, 2017 at 6:49
  • 1
    He's asking for finding duplicates in a List of Dictionaries. Those aren't exact duplicates. Commented Mar 6, 2017 at 6:52
  • Duplicates within a dictionary or any duplicate value? Commented Mar 6, 2017 at 6:55
  • doctor, duplicates in List of dictionaries. Commented Mar 6, 2017 at 7:09

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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);

1 Comment

This works only with one dictionary. But not with a List.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.