我需要同步在线数据库和本地数据库的约会。 这是我到目前为止的代码:比较列表中对象的属性
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