IEqualityComparer使用字符串列表作为比较器

mrb*_*398 4 c# iequalitycomparer

我正在尝试设置一个使用字符串列表作为比较属性的IEqualityComparer.

在下面的两行代码中使用Except和Intersect时,所有记录都被视为"new",并且没有一个被识别为"old".

List<ExclusionRecordLite> newRecords = currentRecords.Except(historicalRecords, new ExclusionRecordLiteComparer()).ToList();
List<ExclusionRecordLite> oldRecords = currentRecords.Intersect(historicalRecords, new ExclusionRecordLiteComparer()).ToList();
Run Code Online (Sandbox Code Playgroud)

这是我的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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 7

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

要回答为什么集合没有覆盖GetHashCode但使用object.GetHashCode返回唯一值的原因:为什么C#没有为集合实现GetHashCode?