在C#中,如何实现对集合中元素的⾃定义排序?

在 C# 中,可以通过多种方式实现对集合中元素的自定义排序,主要包括:

  1. 实现比较接口 IComparer<T>IComparable<T>
  2. 使用 List<T>.Sort 方法并传递自定义比较器
  3. 利用 LINQ 的 OrderByThenBy 方法
  4. 自定义排序逻辑内联传递(如通过 Lambda 表达式)

示例代码

1. 使用 IComparable<T> 接口

适用于对集合中的对象进行默认排序。

using System;
using System.Collections.Generic;

public class Person : IComparable<Person>
{
    public string Name { get; set; }
    public int Age { get; set; }

    public int CompareTo(Person other)
    {
        return Age.CompareTo(other.Age); // 按年龄排序
    }
}

class Program
{
    static void Main()
    {
        List<Person> people = new List<Person>
        {
            new Person { Name = "Alice", Age = 30 },
            new Person { Name = "Bob", Age = 25 },
            new Person { Name = "Charlie", Age = 35 }
        };

        people.Sort();
        foreach (var person in people)
        {
            Console.WriteLine($"{person.Name}, {person.Age}");
        }
    }
}

2. 使用 IComparer<T> 接口

适用于多种排序规则。

using System;
using System.Collections.Generic;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class AgeComparer : IComparer<Person>
{
    public int Compare(Person x, Person y)
    {
        return x.Age.CompareTo(y.Age); // 按年龄排序
    }
}

class Program
{
    static void Main()
    {
        List<Person> people = new List<Person>
        {
            new Person { Name = "Alice", Age = 30 },
            new Person { Name = "Bob", Age = 25 },
            new Person { Name = "Charlie", Age = 35 }
        };

        people.Sort(new AgeComparer());
        foreach (var person in people)
        {
            Console.WriteLine($"{person.Name}, {person.Age}");
        }
    }
}

3. 使用 Lambda 表达式

简化排序逻辑。

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 3, 1, 4, 1, 5, 9 };

        // 按降序排序
        numbers.Sort((x, y) => y.CompareTo(x));

        foreach (var number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

4. 使用 LINQ 的 OrderByThenBy 方法

支持链式排序和延迟执行。

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<string> names = new List<string> { "Alice", "Bob", "Charlie" };

        var sortedNames = names.OrderBy(name => name.Length).ThenBy(name => name);

        foreach (var name in sortedNames)
        {
            Console.WriteLine(name);
        }
    }
}

总结

  • IComparable<T>:适用于为对象定义默认排序。
  • IComparer<T>:适用于需要多种排序规则的场景。
  • Sort 方法结合 Lambda 表达式:适合简单的排序逻辑。
  • LINQOrderByThenBy:适合链式排序和复杂查询场景。

选择排序方式时应根据实际需求选择合适的实现方案。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

面试八股文

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值