Pregunta

If I have the following methods:

public bool Equals(VehicleClaim x, VehicleClaim y)
{           
    bool isDateMatching = this.IsDateRangeMatching(x.ClaimDate, y.ClaimDate);
    // other properties use exact matching
}

private bool IsDateRangeMatching(DateTime x, DateTime y)
{       
    return x >= y.AddDays(-7) && x <= y.AddDays(7);           
}

I am comfortable overriding GetHashcode when the values exactly match but I really have no idea how to do it when a match is within a range like this.

Can anyone help please?

¿Fue útil?

Solución

I agree with Chris that

But if you have Date1 as Oct1, Date2 as Oct6, Date3 as Oct12. Date1 == Date2, and Date2 == Date3, but Date1 != Date3 is a strange behavior and the Equals purpose is not what you should use.

I don't really know if you are developping something new and if you have a database containing your vehicule claims, but I would have associated claims in the database as parent child relationship. What you have to ask yourself is: Is it possible that 2 vehicule claims within your date range can be different? Is there any other property you can use to identify a claim as unique?

Maybe you could resolve your problem this way:

Having a

List<VehicleClaim> RelatedClaims 

property in your VehicleClaim object.

Instead of Equals, use a function

bool IsRelated(VehicleClaim vehiculeClaim)
{ 
  if(all properties except date are equals)
  {  
     // since claims are sorted by date, we could compare only with the last element
     foreach(var c in RelatedClaims){ 
        if (IsDateRangeMatching(this.ClaimDate, c.ClaimDate)) 
           return true;
     }
  }

  return false;
}

and add code to construct your object

List<VehiculeClaim> yourListWithDuplicatesSortedByDate;
List<VehiculeClaim> noDuplicateList = new List<VehiculeClaim>();
foreach(var cwd in yourListWithDuplicatesSortedByDate)
{
  var relatedFound = noDuplicateList.FirstOrDefault(e => e.IsRelated(cwd));

  if (relatedFound != null)
    relatedFound.RelatedClaims.Add(cwd);
  else
    noDuplicateList.Add(cwd);
}

Problem with this, your claims must be sorted by date and it could not be the most efficient way to accomplish that.

Otros consejos

Bear in mind:

If you override the GetHashCode method, you should also override Equals, and vice versa. If your overridden Equals method returns true when two objects are tested for equality, your overridden GetHashCode method must return the same value for the two objects.

http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx

Therefore it seems your GetHashCode override must return the same value for all instances, because each +- 7 day period overlaps its neighbors.

Please don't mark this as the answer. It's an answer but not the answer.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top