我需要同步在線數據庫和本地數據庫的約會。 這是我到目前爲止的代碼:比較列表中對象的屬性
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);
因爲我只是想比較我創立的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
}
不幸的是,這並不工作:
var comparer = new AppointmentEqualityComparer<Appointment>();
IEnumerable<Appointment> diffOnlineOffline = onlineAppointments.Except(localAppointments, comparer);
含義diffOnlineOffline不是空的,但它應該是因爲這兩個列表包含相同的約會。
有什麼想法?
我沒有看到在EqualityComparer任何問題。您是否已經完成了執行並檢查了兩個約會的價值? – rae1
您的哈希碼實現應該使用與您的相等比較相同的屬性,即'AppointmentStart'和'AppointmentEnd'。 – Lee
你是什麼意思@Lee?對不起,但我不太明白你的意思......你能給我一個具體的例子嗎? – libjup