C# List如何进行排序

来源:开发教程作者:河北彩花头衔:网络博主
导读:本期聚焦于小伙伴创作的《C# List如何进行排序》,敬请观看详情,探索知识的价值。以下视频、文章将为您系统阐述其核心内容与价值。如果您觉得《C# List如何进行排序》有用,将其分享出去将是对创作者最好的鼓励。

在C#开发过程中,List集合是存储同类型数据的常用容器,当我们需要对集合中的元素按照数值大小、字符串顺序或者自定义的业务规则排列时,就需要用到List的排序功能。C#为List提供了多种排序实现方式,开发者可以根据不同的场景选择最合适的方案。

C# List如何进行排序

C# List内置Sort方法排序

List类本身提供了Sort方法,这是最基础的排序方式,默认会对元素进行升序排序,要求元素类型实现IComparable接口。

基本类型排序

对于int、string等已经实现IComparable接口的基础类型,直接调用Sort方法即可完成排序。

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 整数List排序
        List<int> numList = new List<int> { 5, 2, 8, 1, 3 };
        numList.Sort();
        Console.WriteLine("整数升序排序结果:");
        foreach (var num in numList)
        {
            Console.Write(num + " ");
        }
        // 输出:1 2 3 5 8

        // 字符串List排序
        List<string> strList = new List<string> { "banana", "apple", "cherry" };
        strList.Sort();
        Console.WriteLine("n字符串升序排序结果:");
        foreach (var str in strList)
        {
            Console.Write(str + " ");
        }
        // 输出:apple banana cherry
    }
}

降序排序

如果需要降序排序,可以调用Sort方法的重载版本,传入Comparison委托或者IComparer实现。

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> numList = new List<int> { 5, 2, 8, 1, 3 };
        // 使用Comparison委托实现降序
        numList.Sort((a, b) => b.CompareTo(a));
        Console.WriteLine("整数降序排序结果:");
        foreach (var num in numList)
        {
            Console.Write(num + " ");
        }
        // 输出:8 5 3 2 1
    }
}

使用LINQ的OrderBy方法排序

除了内置的Sort方法,我们还可以使用LINQ提供的OrderByOrderByDescending方法排序,这种方式不会修改原List,而是返回一个新的排序后的序列,更适合函数式编程风格的场景。

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

class Program
{
    static void Main()
    {
        List<int> numList = new List<int> { 5, 2, 8, 1, 3 };
        // 升序排序,返回新序列
        List<int> ascList = numList.OrderBy(x => x).ToList();
        Console.WriteLine("OrderBy升序结果:");
        foreach (var num in ascList)
        {
            Console.Write(num + " ");
        }

        // 降序排序
        List<int> descList = numList.OrderByDescending(x => x).ToList();
        Console.WriteLine("nOrderByDescending降序结果:");
        foreach (var num in descList)
        {
            Console.Write(num + " ");
        }
    }
}

自定义类型排序

当List中存储的是自定义类的实例时,需要指定排序规则,常见的方式有两种:让自定义类实现IComparable接口,或者创建自定义比较器实现IComparer接口。

实现IComparable接口

让自定义类实现IComparable<T>接口,重写CompareTo方法,定义默认的排序规则。

using System;
using System.Collections.Generic;

// 自定义学生类
class Student : IComparable<Student>
{
    public string Name { get; set; }
    public int Score { get; set; }

    // 按分数升序排序
    public int CompareTo(Student other)
    {
        if (other == null) return 1;
        return this.Score.CompareTo(other.Score);
    }
}

class Program
{
    static void Main()
    {
        List<Student> students = new List<Student>
        {
            new Student { Name = "张三", Score = 85 },
            new Student { Name = "李四", Score = 92 },
            new Student { Name = "王五", Score = 78 }
        };
        students.Sort();
        Console.WriteLine("按分数升序排序的学生列表:");
        foreach (var stu in students)
        {
            Console.WriteLine($"姓名:{stu.Name},分数:{stu.Score}");
        }
    }
}

实现IComparer接口

如果需要多种不同的排序规则,可以创建自定义比较器,实现IComparer<T>接口,排序时传入比较器实例即可。

using System;
using System.Collections.Generic;

class Student
{
    public string Name { get; set; }
    public int Score { get; set; }
}

// 按姓名排序的比较器
class StudentNameComparer : IComparer<Student>
{
    public int Compare(Student x, Student y)
    {
        if (x == null || y == null)
        {
            return 0;
        }
        return string.Compare(x.Name, y.Name);
    }
}

class Program
{
    static void Main()
    {
        List<Student> students = new List<Student>
        {
            new Student { Name = "张三", Score = 85 },
            new Student { Name = "李四", Score = 92 },
            new Student { Name = "王五", Score = 78 }
        };
        // 传入自定义比较器按姓名排序
        students.Sort(new StudentNameComparer());
        Console.WriteLine("按姓名排序的学生列表:");
        foreach (var stu in students)
        {
            Console.WriteLine($"姓名:{stu.Name},分数:{stu.Score}");
        }
    }
}

多条件排序

实际开发中经常需要多条件排序,比如先按分数降序,分数相同再按姓名升序。使用Sort方法可以传入复合的比较逻辑,使用LINQ的OrderBy配合ThenBy也能实现。

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

class Student
{
    public string Name { get; set; }
    public int Score { get; set; }
}

class Program
{
    static void Main()
    {
        List<Student> students = new List<Student>
        {
            new Student { Name = "张三", Score = 85 },
            new Student { Name = "李四", Score = 92 },
            new Student { Name = "王五", Score = 85 }
        };

        // 方式1:使用Sort方法的多条件比较
        students.Sort((a, b) =>
        {
            int scoreCompare = b.Score.CompareTo(a.Score); // 分数降序
            if (scoreCompare != 0)
            {
                return scoreCompare;
            }
            return string.Compare(a.Name, b.Name); // 分数相同按姓名升序
        });
        Console.WriteLine("Sort多条件排序结果:");
        foreach (var stu in students)
        {
            Console.WriteLine($"姓名:{stu.Name},分数:{stu.Score}");
        }

        // 方式2:使用LINQ的OrderBy和ThenBy
        var orderedStudents = students.OrderByDescending(s => s.Score)
                                      .ThenBy(s => s.Name)
                                      .ToList();
        Console.WriteLine("nLINQ多条件排序结果:");
        foreach (var stu in orderedStudents)
        {
            Console.WriteLine($"姓名:{stu.Name},分数:{stu.Score}");
        }
    }
}

排序方法选择建议

不同的排序方式适用场景不同,开发者可以根据需求选择:

  • 如果需要原地修改原List,优先选择Sort方法,性能相对更好
  • 如果需要保留原List,或者偏好函数式编程风格,选择LINQ的OrderBy系列方法
  • 自定义类型排序优先让类实现IComparable接口定义默认规则,特殊排序场景再创建IComparer实现
  • 多条件排序时,Sort方法适合简单规则,OrderBy配合ThenBy可读性更高

C#_List排序方法Sort方法OrderBy自定义排序修改时间:2026-07-06 09:12:35

免责声明:​ 已尽一切努力确保本网站所含信息的准确性。网站内容多为原创整理与精心编撰,观点力求客观中立。本站旨在免费分享,内容仅供个人学习、研究或参考使用。若引用了第三方作品,版权归原作者所有。如内容涉及您的权益,请联系我们处理。
内容垂直聚焦
专注技术核心技术栏目,确保每篇文章深度聚焦于实用技能。从代码技巧到架构设计,为用户提供无干扰的纯技术知识沉淀,精准满足专业提升需求。
知识结构清晰
覆盖从开发到部署的全链路。AI、前端、编程、数据库、服务器、建站、系统层层递进,构建清晰学习路径,帮助用户系统化掌握开发与运维所需的核心技术。
深度技术解析
拒绝泛泛而谈,深入技术细节与实践难点。无论是数据库优化还是服务器配置,均结合真实场景与代码示例进行剖析,致力于提供可直接应用于工作的解决方案。
专业领域覆盖
精准对应开发生命周期。从前端界面到后端编程,从数据库操作到服务器运维,形成完整闭环,一站式满足全栈工程师和运维人员的技术需求。
即学即用高效
内容强调实操性,步骤清晰、代码完整。用户可根据教程直接复现和应用于自身项目,显著缩短从学习到实践的距离,快速解决开发中的具体问题。
持续更新保障
专注既定技术方向进行长期、稳定的内容输出。确保各栏目技术文章持续更新迭代,紧跟主流技术发展趋势,为用户提供经久不衰的学习价值。