c# - 比较包含大量对象的两个列表(第 2 部分)

标签 c# linq performance iequalitycomparer

引用我之前问的问题: Compare two lists that contain a lot of objects

令人印象深刻的是,通过实现 IEqualityComparer 接口(interface)可以看到这种比较的速度有多快:example here

正如我在其他问题中提到的,这种比较有助于我在目标文件夹上备份源文件夹。知道我想同步到文件夹,因此我需要比较文件的日期。每当我做类似的事情时:

public class MyFileComparer2 : IEqualityComparer<MyFile>
{

    public bool Equals(MyFile s, MyFile d)
    {
        return
            s.compareName.Equals(d.compareName) &&
            s.size == d.size &&
            s.deepness == d.deepness &&
            s.dateModified.Date <= d.dateModified.Date;  // This line does not work. 
            // I also tried comparing the strings by converting it to a string and it does
            // not work. It does not give me an error but it does not seem to include the files
            // where s.dateModified.Date < d.dateModified.Date

    }

    public int GetHashCode(MyFile a)
    {
        int rt = (a.compareName.GetHashCode() * 251 + a.size.GetHashCode() * 251 + a.deepness.GetHashCode() + a.dateModified.Date.GetHashCode());

        return rt;

    }
}

如果我可以使用大于号或等于号做类似的事情,那就太好了。我也尝试过使用 tick 属性,但它不起作用。也许我做错了什么。我相信不可能用实现此接口(interface)的小于等号来比较事物。而且,我不明白这个类是如何工作的;我只知道它遍历整个列表的速度令人印象深刻。

最佳答案

您的整个方法存在根本性缺陷,因为您的 IEqualityComparer.Equals 方法不是对称的。这意味着 Equals(file1, file2) 不等于 Equals(file2, file1) 因为您使用小于运算符的方式。

文档:

明确指出:

Notes to Implementers

The Equals method is reflexive, symmetric, and transitive. That is, it returns true if used to compare an object with itself; true for two objects x and y if it is true for y and x; and true for two objects x and z if it is true for x and y and also true for y and z.

Implementations are required to ensure that if the Equals method returns true for two objects x and y, then the value returned by the GetHashCode method for x must equal the value returned for y.

相反,您需要将 IComparable 接口(interface)或 IEqualityComparer 与日期比较结合使用。如果您不这样做,事情可能会暂时奏效,但您稍后会后悔。

关于c# - 比较包含大量对象的两个列表(第 2 部分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6012874/

相关文章:

c# - 如何检测我的库是否在 .Net Core 3 桌面包下运行

c# - 选择合适的对象和合适的方法的策略

c# - Azure AD B2C 声明可以用于 .NET Core Web 应用程序中的授权目的吗?

c# - 生成从 csv 到列表框的列表

java - 正则表达式性能 VS 纯粹迭代的最佳实践

c# - 将轻量级 Web 服务器嵌入到 .net 应用程序(node.js)中?

c# - 明显不与 LINQ 一起工作

c# - 使用 LINQ 读取 Csv

python - 计算大矩阵特征值的最快方法

python - getattr() 与 __dict__ 查找,哪个更快?