首页 > 解决方案 > 字典列表中的字典比较

问题描述

如何在字典列表中找到重复的字典。我知道如何比较两个字典,但是如何循环呢?

List<Dictionary<string, string>> allLists = new List<Dictionary<string, string>>();
 foreach (Dictionary<string, string> allList in allLists)
            {
                
            }

这就是比较两个字典时的操作方式,我希望能够与字典列表类似:

public static void CompareDict()
        {
            Dictionary<string, object> dic1 = new Dictionary<string, object>();
            Dictionary<string, object> dic2 = new Dictionary<string, object>();
            dic1.Add("Key1", new { Name = "abc", Number = "123", Address = "def", Loc = "xyz" });
            dic1.Add("Key2", new { Name = "DEF", Number = "123", Address = "def", Loc = "xyz" });
            dic1.Add("Key3", new { Name = "GHI", Number = "123", Address = "def", Loc = "xyz" });
            dic1.Add("Key4", new { Name = "JKL", Number = "123", Address = "def", Loc = "xyz" });

            dic2.Add("Key1", new { Name = "abc", Number = "123", Address = "def", Loc = "xyz" });
            dic2.Add("Key2", new { Name = "DEF", Number = "123", Address = "def", Loc = "xyz" });
            dic2.Add("Key3", new { Name = "GHI", Number = "123", Address = "def", Loc = "xyz" });
            dic2.Add("Key4", new { Name = "JKL", Number = "123", Address = "def", Loc = "xyz" });
            bool result = dic1.SequenceEqual(dic2);
            Console.WriteLine(result);
        }

标签: c#dictionarycompare

解决方案


最干净的方法可能是创建一个通用字典相等比较器:

public class DictionaryComparer<TKey, TValue> :
    IEqualityComparer<IDictionary<TKey, TValue>>
{
    public bool Equals(IDictionary<TKey, TValue> x, IDictionary<TKey, TValue> y)
    {
        return Enumerable.SequenceEqual(x, y);
    }

    public int GetHashCode(IDictionary<TKey, TValue> d)
    {
        var hash = default(KeyValuePair<TKey, TValue>).GetHashCode();
        
        foreach (var kp in d)
            hash ^= kp.GetHashCode();
            
        return hash;
    }
}

现在,您可以对字典进行分组以检查重复项:

var hasDups = allLists.GroupBy(d => d, new DictionaryComparer<string, string>())
                      .Where(g => g.Count() > 1)
                      .Any();

推荐阅读