C#集合排序的三种方法(List<T>.Sort、LINQ 的 OrderBy、IComparable<T> 接口)

见过不少人、经过不少事、也吃过不少苦,感悟世事无常、人心多变,靠着回忆将往事串珠成链,聊聊感情、谈谈发展,我慢慢写、你一点一点看......

1、使用 List<T>.Sort 方法与自定义比较器
复制代码
public class Person{
  
      public string Name { get; set; }    public int Age { get; set; }}public class PersonComparer : 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 = "A", Age = 15 },            new Person { Name = "B", Age = 25 },            new Person { Name = "C", Age = 35 }        };        people.Sort(new PersonComparer());        foreach (var person in people)        {
  
              Console.WriteLine($"{person.Name}, {person.Age}");        }    }}
2、使用 LINQ 的 OrderBy 方法与自定义键选择器
复制代码
var people = new List<Person>        {
  
              new Person { Name = "Alice", Age = 30 },            new Person { Name = "Bob", Age = 25 },            new Person { Name = "Charlie", Age = 35 }        };        
         var sortedPeople = people.OrderBy(p => p.Age).ToList();
//var sortedPeople = people.OrderBy(p => p.Age).ThenBy(p => p.Name).ToList();        foreach (var person in sortedPeople)        {
  
              Console.WriteLine($"{person.Name}, {person.Age}");        }

3、默认的排序顺序

复制代码
public class Person : IComparable<Person>{
  
      public string Name { get; set; }    public int Age { get; set; }    public int CompareTo(Person other)    {
  
          if (other == null) return 1;        return this.Age.CompareTo(other.Age);    }}
// 然后可以直接使用 Sort 方法,不需要传递比较器people.Sort();

关注我,不失联。有啥问题请留言。

感情恋爱合集https://blog.csdn.net/forever8341/category_12863789.html

职业发展故事https://blog.csdn.net/forever8341/category_12863790.html

常用代码片段https://blog.csdn.net/forever8341/category_12863793.html

程序开发教程https://blog.csdn.net/forever8341/category_12863792.html

自我备考经验 https://blog.csdn.net/forever8341/category_12863791.html

高阶高效代码https://blog.csdn.net/forever8341/category_12873345.html

金融语言解析https://blog.csdn.net/forever8341/category_12877262.html

相关推荐
雨落倾城夏未凉6 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫7 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫8 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6258 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902118 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠9 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫11 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech11 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf13 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m62513 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#