c# - 字典列表中的字典比较
问题描述
如何在字典列表中找到重复的字典。我知道如何比较两个字典,但是如何循环呢?
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);
}
解决方案
最干净的方法可能是创建一个通用字典相等比较器:
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();
推荐阅读
- java - 我应该在 Java 中的哪里添加 IOExceptions?
- azure-functions - 部署 Azure Function 时出现中央目录损坏错误
- node.js - res.on() 方法的含义是什么?
- vba - vba base64图像png解码
- php - 单击时,从多个输入字段中删除图像并将剩余的图像上传到数据库中
- javascript - 无法读取 null 的属性“第一个”
- java - 存储引用和对象的区别?
- python - Python:选择矩阵中每列非零的最后一个值
- javascript - 如何使用类似于我们为文本溢出所做的省略号将标记列表截断为一行?
- mongodb - “模糊”在 MongoDB 的 $searchBeta 聚合阶段如何工作?