[英]IEqualityComparer using list of string as comparer
I'm attempting to setup an IEqualityComparer that uses a list of string as the comparing property. 我正在尝试设置一个使用字符串列表作为比较属性的IEqualityComparer。
When using Except and Intersect in the 2 lines of code below, all records are seen as 'new' and none are recognized as 'old'. 在下面的两行代码中使用Except和Intersect时,所有记录都被视为“new”,并且没有一个被识别为“old”。
List<ExclusionRecordLite> newRecords = currentRecords.Except(historicalRecords, new ExclusionRecordLiteComparer()).ToList();
List<ExclusionRecordLite> oldRecords = currentRecords.Intersect(historicalRecords, new ExclusionRecordLiteComparer()).ToList();
This is my IEqualityComparer class (Words is a List) 这是我的IEqualityComparer类(单词是一个列表)
public class RecordComparer : IEqualityComparer<Record>
{
public bool Equals(Record x, Record y)
{
if (object.ReferenceEquals(x, y))
return true;
if (x == null || y == null)
return false;
return x.Words.SequenceEqual(y.Words);
}
public int GetHashCode(Record obj)
{
return new { obj.Words }.GetHashCode();
}
}
Your GetHashCode
is incorrect. 您的GetHashCode
不正确。 Use one like this: 使用这样的一个:
public override int GetHashCode()
{
if(Words == null) return 0;
unchecked
{
int hash = 19;
foreach (var word in Words)
{
hash = hash * 31 + (word == null ? 0 : word.GetHashCode());
}
return hash;
}
}
To answer why a collection does not override GetHashCode
but uses object.GetHashCode
which returns a unique value: Why does C# not implement GetHashCode for Collections? 要回答为什么集合不重写GetHashCode
但使用object.GetHashCode
返回唯一值的原因: 为什么C#没有为集合实现GetHashCode?
Assuming you're storing Words
in a List
then calling GetHashCode
on it won't give you back a hash of the items in it, instead it'll give you back the hash value from Object.GetHashCode
. 假设您在List
存储Words
,那么在其上调用GetHashCode
将不会返回其中的项的哈希,而是它将从Object.GetHashCode
返回哈希值。
You need to implement your own hash function that enumerates over the words and generates a hash value. 您需要实现自己的哈希函数,该函数枚举单词并生成哈希值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.