I have a class that was previously being used in a HashSet. This has now been changed so that the class is now used in a SortedSet, but the equality test no longer works as it did. I believe this it uses the CompareTo function for both sorting and comparing, and this is by design.
Anyone have any ideas, other than performing my own duplicate checks?
public sealed class DatedID : IEquatable<DatedID>, IComparable
{
readonly DateTime _added;
readonly int _ID;
public DateTime Added
{
get { return _added; }
}
public int ID
{
get { return _ID; }
}
public DatedID(int id)
: this(id, DateTime.Now) {}
public DatedID(int id, DateTime added)
{
id.ThrowDefault("id");
added.ThrowDefault("added");
_ID = id;
_added = added;
}
// Compare
int IComparable.CompareTo(object obj)
{
var other = (DatedID)obj;
// Newest => oldest
return this.Added > other.Added ? -1 : this.Added < other.Added ? 1 : 0;
}
// Equals
public bool Equals(DatedID other)
{
if (other == null) return false;
return this.ID == other.ID;
}
public override bool Equals(object obj)
{
if (obj == null) return false;
var di = obj as DatedID;
return di == null ? false : Equals(di);
}
public override int GetHashCode()
{
return ID.GetHashCode();
}
}
If you mean you need to be able to handle multiple values with different IDs but the same DateTime
, you could include that in your CompareTo
implementation:
// TODO: Implement IComparable<DatedID> as well :)
int IComparable.CompareTo(object obj)
{
var other = (DatedID)obj;
int dateComparison = other.Added.CompareTo(this.Added);
return dateComparison != 0
? dateComparison
: _ID.CompareTo(other._ID);
}
If you mean you don't want to be able to add multiple values with the same ID but different dates, then you can't achieve that with SortedSet
. In SortedSet
, the only measure of equality is if the comparison returns 0.
See more on this question at Stackoverflow