1

所以我有以下struct

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

我在某处执行以下操作

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

现在我想实施System.IComparable<Foo>例如。的优势.Sort()Foo[]

如何将逻辑(从我的特殊/有线OrderBy/ ThenBy)转移到int CompareTo(Foo foo)

4

1 回答 1

5

怎么样的东西:

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);
    }
}
于 2011-11-30T13:32:53.473 回答