2

I have a Dictionary<DateTime, int> defined like this:

public Dictionary<DateTime, int> Days;

Each DateTime is associated to an int. I'd like to have a function which indicates if there is already a DateTime with the same day in my dictionary:

public int GetIntFromDate(DateTime date)
{
    int i = -1;
    if (Days.ContainsKey(date))
    {
        i= CorrespondanceJoursMatchs[date];
    }

    return i;
}

This is perfect but I'd like that the ContainsKey returns true if there is already a DateTime with the same Day+Month+Year (without looking at hours/minutes/seconds).

In fact my dictionary shouldn't allow 2 DateTime index with the same Day/Month/Year.

A solution could be to create a class with only a DateTime attribute and override GetHashCode and Equals, but maybe there's a better solution?

Jay Walker
  • 4,654
  • 5
  • 47
  • 53
user2088807
  • 1,378
  • 2
  • 25
  • 47

1 Answers1

15

It's simple: just implement IEqualityComparer<DateTime> in a way which just uses DateTime.Date, and pass an instance of that implementation to the Dictionary<,> constructor. Sample code:

using System;
using System.Collections.Generic;

class DateEqualityComparer : IEqualityComparer<DateTime>
{
    public bool Equals(DateTime x, DateTime y)
    {
        return x.Date == y.Date;
    }

    public int GetHashCode(DateTime obj)
    {
        return obj.Date.GetHashCode();
    }
}

class Test
{
    static void Main()
    {
        var key1 = new DateTime(2013, 2, 19, 5, 13, 10);
        var key2 = new DateTime(2013, 2, 19, 21, 23, 30);

        var comparer = new DateEqualityComparer();
        var dictionary = new Dictionary<DateTime, string>(comparer);
        dictionary[key1] = "Foo";
        Console.WriteLine(dictionary[key2]); // Prints Foo
    }

}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194