引用我之前问的问题: 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/