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 に答える