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

相关推荐
Scout-leaf3 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530144 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools5 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的5 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21885 天前
.NET 本地Db数据库-技术方案选型
windows·c#
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
lindexi5 天前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言