Consider the following implementation of Page
:
public class Page
{
public List<Attribute> AssociatedAttributes
{
get
{
return new List<Attribute>() {
new Attribute { Value = "a" },
new Attribute { Value = "b" },
new Attribute { Value = "c" },
};
}
}
}
Here the AssociatedAttributes
property is returning a different list each time AssociatedAttributes
is called. Additionally, the actual items in the list are constructed each time the property is called, it's not just returning references to the same exact Attribute
objects. Since Attribute
(I assume) does not override Equals
or GetHashCode
, it will use the default object
implementation, which considers objects equal if and only if they are referencing the same object. Since the objects in your two lists aren't referencing the same objects, none of them are equal to each other, even though they may have the same values internally.
The fact that Attribute
implements IComparable
is irrelivant.
There are several possible things that could be done to change the behavior:
Rather than constructing new objects in the property getter, return references to the same actual objects. This would likely mean having a private backing field for the property, constructing the objects once, and then returning references to the same list.
Override
Equals
andGetHashCode
inAttribute
to be dependent on its values, rather than its reference. Convention would dictate that you only do this if the object is immutable, as dealing with objects that have mutatingGetHashCode
values is...difficult. You could implementIEquatable
in addition to doing this, if you wanted, to provide a statically typedEquals
method. Note that it's vital to overrideGetHashCode
if you implementIEquatable
, if you still want it to be useful.Create a new object that implements
IEqualityComparer<Attribute>
. This would be an object external toAttribute
that knows how to compare them for equality based on something other than theEquals
andGetHashCode
implementation of the object itself. Provide an instance of such a type toIntersect
andDistinct
. (They each have overloads for custom equality comparers.)