'How to check if a list in a dictionary has duplicates in C#?

I have a dictionary

Dictionary<Enum, List<string>> test = new();

I would like to check if the value (List) of this dictionary has duplicates on a specific key.

Dictionary[Key1] = [x, x, y, z] --> this should return that the list on this key has duplicates.

Dictionary[Key2] = [x]

Dictionary[Key3] = [x, y, z]



Solution 1:[1]

Something like this.

void Main()
{
    Dictionary<string, List<string>> test = new()
    {
        { "one", new List<string> { "x", "x", "y", "z" } },
        { "two", new List<string> { "x" } },
        { "three", new List<string> { "x", "y", "z" } },
    };
    
    foreach (var list in test.Where(x=> x.Value.Count() != x.Value.Distinct().Count()).Select(x=> x.Key))
        Console.WriteLine($"{list} has duplicates.");       
}

You might need to check more closely what duplicate means thought. Things like casing etc.

Solution 2:[2]

You can do it with a lambda function

        Dictionary<Enum, List<string>> myDictionary = new Dictionary<Enum, List<string>>();

        List<Enum> myListofKeysWithDuplicates = myDictionary 
                .Where(item => item.Value.GroupBy(x => x)
                       .Where(g => g.Count() > 1).Any())
                .Select(item => item.Key).ToList();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ralf
Solution 2