gpt4 book ai didi

c# - 比较列表中对象的属性

转载 作者:行者123 更新时间:2023-11-30 22:22:39 24 4
gpt4 key购买 nike

我需要同步在线数据库和本地数据库的约会。到目前为止,这是我的代码:

        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 不是空的,但它应该是空的,因为两个列表包含相同的约会。

有什么想法吗?

最佳答案

您的GetHashCode 方法应该使用用于相等性的属性。目前,您认为相等的对象可能没有相同的哈希码。

你可以这样使用:

public int GetHashCode(T obj)
{
return 41 * (41 * (41 * (41 + obj.getAppointmentStart().GetHashCode()))
+ obj.getAppointmentEnd().GetHashCode());
}

关于c# - 比较列表中对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13779862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com