I need to synchronize appointments of an online database and a local database.
That’s my code so far:
List<Appointment> onlineAppointments = new List<Appointment>();
List<Appointment> localAppointments = new List<Appointment>();
Appointment appointment01 = new Appointment(new DateTime(2012, 12, 24, 17, 30, 00), new DateTime(2012, 12, 24, 17, 45, 00), name, 123, "comment", 0, "test", 123, 1, DateTime.Now);
Appointment appointment02 = new Appointment(new DateTime(2012, 12, 24, 17, 30, 00), new DateTime(2012, 12, 24, 17, 45, 00), name, 123, "comment", 0, "test", 123, 1, DateTime.Now);
onlineAppointments.Add(appointment01);
localAppointments.Add(appointment02);
Since I only want to compare some properties of the object I have created an IEqualityComparer:
public class AppointmentEqualityComparer<T> : IEqualityComparer<T> where T : Appointment
{
#region IEqualityComparer<T> Members
public bool Equals(T x, T y)
{
return (x == null && y == null) || ((x != null && y != null) &&
(x.getAppointmentStart() == y.getAppointmentStart() &&
x.getAppointmentEnd() == y.getAppointmentEnd())
);
}
/// </exception>
public int GetHashCode(T obj)
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
return obj.GetHashCode();
}
#endregion
}
Unfortunately this does not work:
var comparer = new AppointmentEqualityComparer<Appointment>();
IEnumerable<Appointment> diffOnlineOffline = onlineAppointments.Except(localAppointments, comparer);
Meaning diffOnlineOffline is not empty but it should be since both lists contain the same appointment.
Any idea?
Your
GetHashCodemethod should use the properties used for equality. At the moment, objects you want to consider equal will probably not have the same hash code.You can use something like this: