redcodefinal
redcodefinal

Reputation: 909

Sort SortedSet by item member

Consider this class

public class A
{
     float Order
     string Name
     public A(float order, string name)
     {
           Order = order;
           Name = name;
     }
}

If I were to add this to a SortedSet<A> how would it know which member to order it by? How would I specify this, if I even can in the first place. I imagine that the best performance of the set would be sorting it on add, not adding then sorting through Sort().

Upvotes: 3

Views: 2734

Answers (2)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

Assuming that you change the accessibility so that you can read the members of A from outside the class, you can simply do:

new SortedSet<A>(Comparer<A>.Create((a1, a2) => a1.Order.CompareTo(a2.Order)))

This requires .NET 4.5 or later.

Remember that NaN will compare less than everything else.

If you do not pass in your own comparer to the constructor, it will be checked if each instance of A is of a run-time type which implements IComparable<> or IComparable. If not, an error is produced when adding to the SortedSet<A>.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

SortedSet<A> will expect your class to implement IComparable<A>. Alternatively, you can supply a comparator of type IComparer<A> to do the ordering externally to your class, like this:

class ComparerForClassAByOrder : IComparer<A> {
    public int Compare(A left, A right) {
        return Math.Sign(left.Order-right.Order);
    }
}

class ComparerForClassAByName : IComparer<A> {
    public int Compare(A left, A right) {
        return left.Name.CompareTo(right.Name);
    }
}

Now you can create two sorted sets using different comparators:

var soredByOrder = new SortedSet<A>(new ComparerForAByOrder());
var soredByName = new SortedSet<A>(new ComparerForAByName());

Upvotes: 5

Related Questions