C# – Find duplicate values in a dictionary

Dictionaries contain key/value pairs. The keys must be unique, but the values can be repeated many times. When you want to find duplicate values, the simplest option is to use Linq methods GroupBy() and Where(), like this:

using System.Linq;
using System.Collections.Generic;

var dictionary = new Dictionary<string, int>
    ["Bob"] = 1,
    ["Teddy"] = 1,
    ["Linda"] = 2,
    ["Tina"] = 2,
    ["Gene"] = 3

var duplicateValueGroups = dictionary.GroupBy(kvp => kvp.Value).Where(grp => grp.Count() > 1);
Code language: C# (cs)

Note: I initialized the dictionary with a few duplicate values.

This groups the dictionary key/value pairs by value. The group keys (not to be confused with dictionary keys) are the unique values in the dictionary (1,2,3 in this example). These groups have one or more KeyValuePair objects. Where() is then used to select groups that have more than one KeyValuePair associated with the value.

To see the duplicate values and the keys associated with them, you can loop through the groups and their KeyValuePair objects, like this:

foreach(var grp in duplicateValueGroups)
    Console.WriteLine($"Duplicate value={grp.Key}");
    foreach(var kvp in grp)
Code language: C# (cs)

This outputs the following:

Duplicate value=1
Duplicate value=2
        Key=TinaCode language: plaintext (plaintext)

Leave a Comment