简体   繁体   English

覆盖字典 <Datetime,int> &#39;ContainsKey

[英]Override Dictionary<Datetime,int> 's ContainsKey

I have a Dictionary<DateTime, int> defined like this: 我有一个Dictionary<DateTime, int>定义如下:

public Dictionary<DateTime, int> Days;

Each DateTime is associated to an int . 每个DateTime都与int相关联。 I'd like to have a function which indicates if there is already a DateTime with the same day in my dictionary: 我想要一个函数来指示我的字典中是否已存在同一天的DateTime

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). 这是完美的但我想如果已经有一个具有相同日+月+年的DateTime (不查看小时/分钟/秒),则ContainsKey返回true

In fact my dictionary shouldn't allow 2 DateTime index with the same Day/Month/Year. 事实上,我的字典不应该允许2个DateTime索引具有相同的日/月/年。

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? 一个解决方案可能是创建一个只有DateTime属性的类并覆盖GetHashCodeEquals ,但也许有更好的解决方案?

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. 这很简单:只需使用DateTime.Date实现IEqualityComparer<DateTime> ,并将该实现的实例传递给Dictionary<,>构造函数。 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
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM