我正在尝试设置一个使用字符串列表作为比较属性的 IEqualityComparer。
在下面的 2 行代码中使用 Except 和 Intersect 时,所有记录都被视为"new",没有一个被识别为“旧”。
List<ExclusionRecordLite> newRecords = currentRecords.Except(historicalRecords, new ExclusionRecordLiteComparer()).ToList();
List<ExclusionRecordLite> oldRecords = currentRecords.Intersect(historicalRecords, new ExclusionRecordLiteComparer()).ToList();
这是我的 IEqualityComparer 类(Words 是一个列表)
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
它返回一个唯一值:Why does C# not implement GetHashCode for Collections?
关于c# - IEqualityComparer 使用字符串列表作为比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26469493/