通过两个属性比较两个对象

发布于 2024-09-27 01:47:35 字数 124 浏览 0 评论 0原文

如何使用两个属性对列表中的两个对象进行排序,一个按升序,另一个按降序。当使用 linq 时,它说我需要实现 IComparer 接口,但不确定如何通过同时使用两个属性来比较两个对象。

按姓名升序和年龄降序说出人员类别。

How to sort two objects in a list by using two properties one by ascending and the other by descending order. when linq is used it says i need to implement IComparer interface but not sure how to compare two objects by using two properties at once.

Say Person class by Name ascending and Age descending.

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

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

发布评论

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

评论(3

江城子 2024-10-04 01:47:35

那么,您需要决定哪个是您的主要比较。仅当第一个比较给出相等时才使用辅助比较。例如:(

public int Compare(Person p1, Person p2)
{
    int primary = p1.Name.CompareTo(p2.Name);
    if (primary != 0)
    {
        return primary;
    }
    // Note reverse order of comparison to get descending
    return p2.Age.CompareTo(p1.Age);
}

这可以通过各种方式写得更紧凑,但我将其保持得非常明确,以便您可以理解这些概念。)

请注意,在 MiscUtil 我有一些构建块,因此您可以使用 lambda 表达式轻松构建比较器、组合比较器等。

Well, you need to decide which is your primary comparison. Only use the secondary comparison if the first one gives equality. For example:

public int Compare(Person p1, Person p2)
{
    int primary = p1.Name.CompareTo(p2.Name);
    if (primary != 0)
    {
        return primary;
    }
    // Note reverse order of comparison to get descending
    return p2.Age.CompareTo(p1.Age);
}

(This can be written more compactly in various ways, but I've kept it very explicit so you can understand the concepts.)

Note that in MiscUtil I have some building blocks so you can easily construct comparers using lambda expressions, compose comparers etc.

百合的盛世恋 2024-10-04 01:47:35

如果您想创建列表的新副本(以便原始列表中仍然保留原始订单),您可以执行以下操作:

List<Person> unsortedList;

sortedList = unsortedList.OrderBy(p => p.Name).ThenByDescending(p => p.Age);

If you want to create a new copy of the list (so you still have the original order in your original list), you can do this:

List<Person> unsortedList;

sortedList = unsortedList.OrderBy(p => p.Name).ThenByDescending(p => p.Age);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文