我想实现的是对一个日期比较容忍的IEqualityComparer
。我也看过this question。问题是我无法使用解决方法,因为我在LINQ .GroupJoin()
中使用IEqualityComparer
。我已经尝试了一些允许宽容的实现。我可以让Equals()
工作,因为我有两个对象,但我不知道如何实现GetHashCode()
。使用的IEqualityComparer的GetHashCode的公差
我最好的尝试看起来是这样的:
public class ThingWithDateComparer : IEqualityComparer<IThingWithDate>
{
private readonly int _daysToAdd;
public ThingWithDateComparer(int daysToAdd)
{
_daysToAdd = daysToAdd;
}
public int GetHashCode(IThingWithDate obj)
{
unchecked
{
var hash = 17;
hash = hash * 23 + obj.BirthDate.AddDays(_daysToAdd).GetHashCode();
return hash;
}
}
public bool Equals(IThingWithDate x, IThingWithDate y)
{
throw new NotImplementedException();
}
}
public interface IThingWithDate
{
DateTime BirthDate { get; set; }
}
随着.GroupJoin()
建设HashTable
出GetHashCode()
它适用的日子同时添加到/所有对象。这不起作用。
是daysTo添加宽容,因为在1月5日等于1月6日容忍1天?这种相等的定义不是传递性的,所以我怀疑可以在每个对象返回相同哈希码的简单解决方案之外正确使用IEqualityComparer来实现。 –
忘记它。将'GroupJoin'替换为'SelectMany'和简单的'Where'(不是很高效,但应该可以工作)。 –
@mikez是的,那是宽容。命名很糟糕。如果我无法完成这项工作,我将只实现一个定制版本的'GroupJoin()'。 –