【发布时间】:2017-05-20 10:16:07
【问题描述】:
我正在尝试实现一个IEqualityComparer,它对日期比较有一个容差。我还研究了this question。问题是我无法使用解决方法,因为我在 LINQ .GroupJoin() 中使用了IEqualityComparer。我已经尝试了一些允许容忍的实现。我可以让Equals() 工作,因为我有两个对象,但我不知道如何实现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() 在GetHashCode() 之外构建HashTable,它将应用天数添加到两个/所有对象。这不起作用。
【问题讨论】:
-
dayToAdd 容差,如 1 月 5 日等于 1 月 6 日,在 1 天的容差内吗?这个相等的定义不是传递的,所以我怀疑在为每个对象返回相同哈希码的简单解决方案之外使用 IEqualityComparer 是否可以正确实现。
-
算了。将
GroupJoin替换为SelectMany和简单的Where(性能不是很好,但应该可以)。 -
@mikez 是的,这就是容差。只是名字不好。如果我不能完成这项工作,我将只实现
GroupJoin()的自定义版本。 -
@IvanStoev 性能是个问题。我们匹配的当前解决方案使用 where 并且它提供了可怕的性能。通过使用
GroupJoin(),我能够将 9 小时的过程缩短到几毫秒。 -
我知道(并且总是关心 .poerformance)。但慢工作总比不工作好。真正的用例是什么,我们可以考虑别的吗?
标签: c# linq hashtable date-range iequalitycomparer