如何将我的特殊订购实施为 CompareTo

发布于 2024-12-19 04:33:47 字数 704 浏览 3 评论 0原文

所以我有以下 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() 的优点。

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

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)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

虚拟世界 2024-12-26 04:33:47

怎么样:

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);
    }
}

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);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文