4

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.

dotnetnoob
  • 10,783
  • 20
  • 57
  • 103

2 Answers2

8

Implement IComparer and pass it to the SortedSet constructor;

See:

https://msdn.microsoft.com/en-us/library/dd395024%28v=vs.110%29.aspx

For example: I use this

internal class SortedIndex
{
    public double Comparable { get; set; }
    public int Index { get; set; }
}

internal class SortedIndexComparar : IComparer<SortedIndex>
{
    public int Compare(SortedIndex x, SortedIndex y)
    {
        return x.Comparable.CompareTo(y.Comparable);
    }
}
Meirion Hughes
  • 24,994
  • 12
  • 71
  • 122
2

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Good point in the last paragraph - the items are added to the set by a per user so date time should be sufficient in this case. – dotnetnoob Jan 21 '15 at 12:45
  • @dotnetnoob: That doesn't follow necessarily - for example, if it's a "building entrance event" then the same user could enter the building multiple times on the same date. But I'll assume that the extra context you've got makes it okay :) – Jon Skeet Jan 21 '15 at 12:49