Search code examples
c#-4.0icomparable

How do I implement my special ordering as CompareTo


So I have following struct

public struct Foo
{
    public readonly int FirstLevel;
    public readonly int SecondLevel;
    public readonly int ThirdLevel;
    public readonly int FourthLevel;
}

Somewhere I do the following

var sequence = new Foo[0];
var orderedSequence = sequence
    .OrderBy(foo => foo.FirstLevel)
    .ThenBy(foo => foo.SecondLevel)
    .ThenBy(foo => foo.ThirdLevel)
    .ThenBy(foo => foo.FourthLevel);

Now I would like to implement System.IComparable<Foo> to take eg. advantage of .Sort() of Foo[].

How do I transfer the logic (from my special/wired OrderBy/ThenBy) to int CompareTo(Foo foo)?


Solution

  • What about something like:

    public struct Foo : IComparable<Foo>
    {
        public readonly int FirstLevel;
        public readonly int SecondLevel;
        public readonly int ThirdLevel;
        public readonly int FourthLevel;
    
        public int CompareTo(Foo other)
        {
            int result;
    
            if ((result = this.FirstLevel.CompareTo(other.FirstLevel)) != 0)
                return result;
            else if ((result = this.SecondLevel.CompareTo(other.SecondLevel)) != 0)
                return result;
            else if ((result = this.ThirdLevel.CompareTo(other.ThirdLevel)) != 0)
                return result;
            else 
                return this.FourthLevel.CompareTo(other.FourthLevel);
        }
    }