Search code examples
c#linqperformanceiequalitycomparer

Compare two lists that contain a lot of objects (2th part)


Referring to the question that I previously asked: Compare two lists that contain a lot of objects

It is impressive to see how fast that comparison is maide by implementing the IEqualityComparer interface: example here

As I mentioned in my other question this comparison helps me to backup a sourse folder on a destination folder. Know I want to sync to folders therefore I need to compare the dates of the files. Whenever I do something like:

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;

    }
}

It will be nice if I could do something similar using greater or equal than signs. I also tried using the tick property and it does not work. Maybe I am doing something wrong. I believe it is not possible to compare things with the less than equal sign implementing this interface. Moreover, I don't understand how this Class works; I just know it is impressive how fast it iterates through the whole list.


Solution

  • Since the DateTime objects are different in the case when one DateTime is less than the other, you get different hashcodes for the objects s and d and the Equals method is not called. In order for your comparison of the dates to work, you should remove the date part from the GetHashCode method:

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