I'm looking at replacing a HashSet with a SortedSet because it is better suited to the data I'm storing.
However, all the examples I've seen so far relate to storing simple objects - int's, strings etc.
I want to implement this for a custom class with a number of properties, however the class also includes a date that I want to use as the 'indexer'.
The question is how do I go about declaring a custom indexer for the set to use which will override the default behaviour?
Thanks in advance.
Assuming by "indexer" you mean "ordering", you just make your type implement IComparable<Foo>
, and provide a CompareTo
method which compares the date within this
to the date within the other Foo
.
Or you could implement IComparer<Foo>
(with a Compare(Foo x, Foo y)
method) and pass that to the SortedSet
constructor.
In both cases, you're basically just allowing the sorted set to work out which should come before another - it then uses that to perform comparisons when it needs to.
Note that this means any values which have the same date will be seen as equal, so you'd only be able to have a single value for each date. If that's not what you want, your comparison will need to use some other discriminator for when the dates are equal.
See more on this question at Stackoverflow