I have two custom classes, ChangeRequest
and ChangeRequests
, where a ChangeRequests
can contain many ChangeRequest
instances.
public class ChangeRequests : IXmlSerializable, ICloneable, IEnumerable<ChangeRequest>,
IEquatable<ChangeRequests> { ... }
public class ChangeRequest : ICloneable, IXmlSerializable, IEquatable<ChangeRequest>
{ ... }
I am trying to do a union of two ChangeRequests
instances. However, duplicates do not seem to be removed. My MSTest unit test is as follows:
var cr1 = new ChangeRequest { CRID = "12" };
var crs1 = new ChangeRequests { cr1 };
var crs2 = new ChangeRequests
{
cr1.Clone(),
new ChangeRequest { CRID = "34" }
};
Assert.AreEqual(crs1[0], crs2[0], "First CR in both ChangeRequests should be equal");
var unionedCRs = new ChangeRequests(crs1.Union<ChangeRequest>(crs2));
ChangeRequests expected = crs2.Clone();
Assert.AreEqual(expected, unionedCRs, "Duplicates should be removed from a Union");
The test fails in the last line, and unionedCRs
contains two copies of cr1
. When I tried to debug and step through each line, I had a breakpoint in ChangeRequest.Equals(object)
on the first line, as well as in the first line of ChangeRequest.Equals(ChangeRequest)
, but neither were hit. Why does the union contain duplicate ChangeRequest
instances?
Edit: as requested, here is ChangeRequests.Equals(ChangeRequests)
:
public bool Equals(ChangeRequests other)
{
if (ReferenceEquals(this, other))
{
return true;
}
return null != other && this.SequenceEqual<ChangeRequest>(other);
}
And here's ChangeRequests.Equals(object)
:
public override bool Equals(object obj)
{
return Equals(obj as ChangeRequests);
}
Edit: I overrode GetHashCode
on both ChangeRequest
and ChangeRequests
but still in my test, if I do IEnumerable<ChangeRequest> unionedCRsIEnum = crs1.Union<ChangeRequest>(crs2);
, unionedCRsIEnum
ends up with two copies of the ChangeRequest
with CRID
12.
Edit: something has to be up with my Equals
or GetHashCode
implementations somewhere, since Assert.AreEqual(expected, unionedCRs.Distinct(), "Distinct should remove duplicates");
fails, and the string representations of expected
and unionedCRs.Distinct()
show that unionedCRs.Distinct()
definitely has two copies of CR 12.