C#中集合泛型排序

使用默认比较器

如果集合中的元素实现了 IComparable<T> 接口,List<T> 会使用该接口的默认实现来排序。

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> numbers = new List<int> { 5, 3, 8, 1, 2 };
        numbers.Sort();
        
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

使用自定义比较器

如果需要自定义排序规则,可以实现 IComparer<T> 接口,并在排序时传入该接口的实现。

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<string> words = new List<string> { "apple", "orange", "banana", "grape" };
        words.Sort(new CustomComparer());
        
        foreach (string word in words)
        {
            Console.WriteLine(word);
        }
    }
}

public class CustomComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        // 逆序排序
        return y.CompareTo(x);
    }
}

使用 Lambda 表达式

可以通过传入一个 Lambda 表达式来定义排序规则。

using System;
using System.Collections.Generic;

public class Program
{
    public 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((x, y) => x.Age.CompareTo(y.Age));
        
        foreach (Person person in people)
        {
            Console.WriteLine($"{person.Name} - {person.Age}");
        }
    }
}

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

使用 LINQ

除了 List<T>Sort 方法,还可以使用 LINQ 的 OrderByOrderByDescending 方法来对集合进行排序。

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

public class Program
{
    public static void Main()
    {
        List<int> numbers = new List<int> { 5, 3, 8, 1, 2 };
        var sortedNumbers = numbers.OrderBy(n => n).ToList();
        
        foreach (int number in sortedNumbers)
        {
            Console.WriteLine(number);
        }
    }
}

这些示例展示了如何使用不同的方式对集合泛型进行排序。根据具体需求,可以选择适合的排序方法。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值