如何检查字典中的列表是否在 C# 中有重复项?

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

我有字典

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

我想检查这个字典的值(列表)是否在特定键上有重复项。

Dictionary[Key1] = [x, x, y, z] --> 这应该 return 这个键上的列表有重复项。

字典[Key2] = [x]

字典[Key3] = [x, y, z]

像这样。

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.");       
}

您可能需要更仔细地检查重复的意思。外壳之类的东西

您可以使用 lambda 函数来完成

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