SortedSet - custom order when storing a class object

偶尔善良 提交于 2019-12-11 03:15:42

问题


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.


回答1:


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



回答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.



来源:https://stackoverflow.com/questions/28067196/sortedset-custom-order-when-storing-a-class-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!