IEqualityComparer使用字符串列表作为比较器
本文关键字:比较器 列表 字符串 IEqualityComparer | 更新日期: 2023-09-27 18:27:15
我正在尝试设置一个使用字符串列表作为比较属性的IEqualityComparer。
在下面的2行代码中使用Except和Intersect时,所有记录都被视为"新",没有一条记录被识别为"旧"。
List<ExclusionRecordLite> newRecords = currentRecords.Except(historicalRecords, new ExclusionRecordLiteComparer()).ToList();
List<ExclusionRecordLite> oldRecords = currentRecords.Intersect(historicalRecords, new ExclusionRecordLiteComparer()).ToList();
这是我的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();
}
}
您的GetHashCode
不正确。使用这样一个:
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;
}
}
为了回答为什么集合不覆盖GetHashCode
,而是使用返回唯一值的object.GetHashCode
:为什么C#不为集合实现GetHashCode?
假设您将Words
存储在List
中,那么对其调用GetHashCode
不会返回其中项目的哈希值,而是会返回Object.GetHashCode
中的哈希值。
您需要实现自己的散列函数,该函数枚举单词并生成散列值。