我正在尝试比较包含自定义对象的 2 个列表(包装在一个对象中)。我不关心顺序,但如果列表 1 包含“1,2,3,4”,那么列表 2 必须且仅包含这些元素。例如:“4,2,3,1”
基于比较两个 List<T> 对象是否相等,忽略顺序 忽略顺序我使用了 except 和 Any 但它没有给我想要的结果。
如果我使用Assert.Equals
它失败,但Assert.IsTry(list1.equals(list2))
成功。
此外,如果我删除 Equals 和 GetHashCode 实现,那么两个测试都会失败。
public class AppointmentCollection : List<Appointment>
{
public override bool Equals(object obj)
{
var appCol = obj as AppointmentCollection;
if (appCol == null)
{
return false;
}
return (appCol.Count == this.Count) && !(this.Except(appCol).Any());
}
public override int GetHashCode()
{
unchecked
{
//use 2 primes
int hash = 17;
foreach (var appointment in this)
{
hash = hash * 19 + appointment.GetHashCode();
}
return hash;
}
}
}
public class Appointment
{
public string Title {get; set;}
public DateTime StartTime {get; set;}
public DateTime EndTime { get; set;}
public override bool Equals(object obj)
{
var appointment = obj as Appointment;
if (appointment == null)
{
return false;
}
return Title.Equals(appointment.Title) &&
StartTime.Equals(appointment.StartTime) &&
EndTime.Equals(appointment.EndTime);
}
public override int GetHashCode()
{
unchecked
{
//use 2 primes
int hash = 17;
hash = hash * 19 + Title.GetHashCode();
hash = hash * 19 + StartTime.GetHashCode();
hash = hash * 19 + EndTime.GetHashCode();
return hash;
}
}
}
[Test]
public void TestAppointmentListComparisonDifferentOrder()
{
var appointment1 = new Appointment(
"equals test1",
new DateTime(2013, 9, 4),
new DateTime(2013, 9, 4));
var appointment2 = new Appointment(
"equals test2",
new DateTime(2013, 9, 4),
new DateTime(2013, 9, 4));
var list1 = new AppointmentCollection() { appointment1, appointment2 };
var list2 = new AppointmentCollection() { appointment2, appointment1 };
//With Equals/GetHashCode in AppointmentCollection implemented
CollectionAssert.AreEqual(list1, list2); //fails
Assert.IsTrue(list1.Equals(list2)); //success
//Without Equals/GetHashCode in AppointmentCollection implemented
CollectionAssert.AreEqual(list1, list2); //fails
Assert.IsTrue(list1.Equals(list2)); //fails
}