如何解决词典列表中词典的比较
如何在词典列表中找到重复的词典。我知道如何比较两个字典,但是如何循环使用?
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",Loc = "xyz" });
dic1.Add("Key3",new { Name = "GHI",Loc = "xyz" });
dic1.Add("Key4",new { Name = "JKL",Loc = "xyz" });
dic2.Add("Key1",Loc = "xyz" });
dic2.Add("Key2",Loc = "xyz" });
dic2.Add("Key3",Loc = "xyz" });
dic2.Add("Key4",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();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。