Question

J'ai struct suivant

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

Quelque part, je fais ce qui suit

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

Maintenant, je voudrais mettre en œuvre System.IComparable<Foo> prendre par exemple. avantage de .Sort() de Foo[].

Comment puis-je transférer la logique (de ma spéciale / filaire OrderBy / ThenBy) à int CompareTo(Foo foo)?

Était-ce utile?

La solution

Qu'en est-il quelque chose comme:

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);
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top