skip to Main Content

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]

2

Answers


  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.

    Login or Signup to reply.
  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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search