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]
CodePudding user response:
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.
CodePudding user response:
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();