简体   繁体   中英

SortedSet - custom order when storing a class object

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.

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);
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM