Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IComparer on multiple values

Tags:

.net

Is it possible to sort a list using two values in an object with iComparer?

I've got a custom comparer class that sorts based on value1. But what's the best way to get a sort on value1 and value2?

Would sorting the list by value2 then value1 work?

like image 421
steve Avatar asked Dec 14 '22 04:12

steve


1 Answers

Your IComparer class should handle it. For example:

public class ThingComparer : IComparer
{
    public int Compare(object x, object y)
    {
        // null- and type-checking omitted for clarity

        // sort by A, B, and then C

        if (x.A != y.A) return x.A.CompareTo(y.A);
        if (x.B != y.B) return x.B.CompareTo(y.B);
        return x.C.CompareTo(y.C);
    }
}
like image 73
mqp Avatar answered Jan 02 '23 16:01

mqp