I faced a problem when I tried to get the intersection between two lists of DateTime. I wanted to have the intersection only by comparing dates and not dates and time. If I use the LINQ method Intersect on my lists, it will not fit what I want because if the date match but not the time (like different seconds) it will not be part of the intersection.

Of course, I can make my own Intersect method that will test only the date but it’s a little bit overkill. The easy way is to use an IEqualityComparer and pass it to the Intersect method. Here is the implementation I used :

public class DateEqualityComparer : IEqualityComparer<DateTime>
{
    public bool Equals(DateTime date1, DateTime date2)
    {
        return GetHashCode(date1) == GetHashCode(date2);
    }

    public int GetHashCode(DateTime date)
    {
        var hashCode = date.Year ^ date.Month ^ date.Day;
        return hashCode.GetHashCode();
    }
}

A little sample of the case :

public void IntersectDates()
{
    var dates1 = new List<DateTime>
    {
        DateTime.Now,
        DateTime.Now.AddDays(1).AddSeconds(5),
        DateTime.Now.AddDays(3).AddSeconds(10)
    };
    // 05/10/2017 21:40:24
    // 06/10/2017 21:40:29
    // 08/10/2017 21:40:34

    var dates2 = new List<DateTime>
    {
        DateTime.Now,
        DateTime.Now.AddDays(2).AddSeconds(15),
        DateTime.Now.AddDays(3).AddSeconds(20)
    };
    // 05/10/2017 21:40:24
    // 07/10/2017 21:40:39
    // 08/10/2017 21:40:44

    var dateEqualityComparer = new DateEqualityComparer();
    var intersectList = dates1.Intersect(dates2, dateEqualityComparer).ToList();
    Log(intersectList);
}

private static void Log(IEnumerable<DateTime> list)
{
    foreach (var someClass in list)
    {
        Console.WriteLine(someClass.ToString());
    }
    // 05/10/2017
    // 08/10/2017
}