我想實現的是對一個日期比較容忍的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()'。 –