2

嗯,我正面临 IEquatable (C#) 的问题。正如您在下面的代码中看到的那样,我有一个实现 IEquatable 的类,但它的“Equals”方法无法实现。我的目标是:我的数据库中有一个日期时间列,我只想区分日期,而不考虑“时间”部分。

例如:12-01-2014 23:14 将等于 12-01-2014 18:00。

namespace MyNamespace
{
    public class MyRepository
    {
        public void MyMethod(int id)
        {
            var x = (from t in context.MyTable
                     where t.id == id
                     select new MyClassDatetime()
                     {
                         Dates = v.Date
                     }).Distinct().ToList();
        }
    }


public class MyClassDatetime : IEquatable<MyClassDatetime>
{
    public DateTime? Dates { get; set; }

    public bool Equals(MyClassDatetime other)
    {
        if (other == null) return false;
        return (this.Dates.HasValue ? this.Dates.Value.ToShortDateString().Equals(other.Dates.Value.ToShortDateString()) : false);
    }

    public override bool Equals(object other)
    {
        return this.Equals(other as MyClassDatetime );
    }

    public override int GetHashCode()
    {
        int hashDate = Dates.GetHashCode();
        return hashDate;
    }
}
}

你知道我怎样才能让它正常工作或做我需要的其他选择吗?谢谢!!

4

2 回答 2

8

GetHashCode对于所需的相等语义,您的实现不正确。那是因为它为您想要比较相等的日期返回不同的哈希码,这是一个错误

要修复它,请将其更改为

public override int GetHashCode()
{
    return Dates.HasValue ? Dates.Value.Date.GetHashCode() : 0;
}

您还应该Equals以同样的精神进行更新,弄乱日期的字符串表示不是一个好主意:

public bool Equals(MyClassDatetime other)
{
    if (other == null) return false;
    if (Dates == null) return other.Dates == null;
    return Dates.Value.Date == other.Dates.Value.Date;
}

更新:正如 usr非常正确地指出的那样,由于您在 IQueryable 上使用 LINQ,因此投影和Distinct调用将被转换为存储表达式,并且此代码仍然不会运行。要解决这个问题,您可以使用中间AsEnumerable调用:

var x = (from t in context.MyTable
         where t.id == id
         select new MyClassDatetime()
         {
             Dates = v.Date
         }).AsEnumerable().Distinct().ToList();
于 2014-07-08T14:44:13.403 回答
0

感谢回复,但它仍然没有解决我的问题。

我终于找到了一种方法,但不使用 IEquatable。

var x = (from t in context.MyTable where t.Id == id select EntityFunctions.CreateDateTime(t.Date.Value.Year, t.Date.Value.Month,t.Date.Value.Day, 0, 0, 0)).Distinct();

=)

于 2014-07-10T18:03:24.130 回答