【发布时间】:2014-07-08 14:41:27
【问题描述】:
我遇到了 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;
}
}
}
你知道我怎样才能让它正常工作或其他选项来做我需要的吗? 谢谢!!
【问题讨论】:
-
“两个相等的对象返回相等的哈希码。” msdn.microsoft.com/en-us/library/…
标签: c# entity-framework datetime distinct iequatable