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

标签 c# iequalitycomparer

我正在尝试设置一个使用字符串列表作为比较属性的 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/

相关文章:

c# - 将以空字符结尾的字符串列表从外部函数返回到 .NET

c# - 在 C# 中比较两个 List<MyClass>

c# - 如何使用 LINQ 查找集合中的重叠(不是重复,而是查找重叠)

.net - IStructuralEquatable 和 IStructuralComparable 解决什么问题?

c# - 在 MVC3 Razor 中使用 LinQ to Sql 将 Customer.customerID 输入 Advert.cutomerID

c# - ASP.NET MVC 6 中的属性路由正则表达式约束错误

c# - 如何从 txt 文件中正确读取瑞典语字符

c# - 查找c#中某个子字符串后面出现的第一个数字的索引

c# - 子类 HashSet 以便它在另一个集合中使用时始终使用某个 IEqualityComparer

c# - 如何强制 HashSet 重新散列成员?