在C#的日常开发里,我们经常需要对存储数据的List集合进行排序操作,其中使用OrderBy实现升序排列是最常用的方法之一,掌握这个技巧能大幅提升处理集合数据的效率。

OrderBy方法的基本说明
OrderBy是System.Linq命名空间下的扩展方法,专门用于对集合中的元素按照指定的键进行升序排序,返回的是一个有序的新序列,不会修改原始集合的内容。它接受一个Func委托作为参数,用来指定排序的依据字段。
基本类型List的升序排序
对于存储int、string等基本类型的List,使用OrderBy排序非常简单,直接传入元素本身作为排序键即可。以下是一个整数List升序排序的示例:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// 初始化一个无序的整数List
List<int> numList = new List<int> { 5, 2, 8, 1, 3 };
// 使用OrderBy进行升序排序
var sortedList = numList.OrderBy(num => num).ToList();
// 输出排序结果
Console.WriteLine("升序排序后的结果:");
foreach (var num in sortedList)
{
Console.Write(num + " ");
}
// 输出结果:1 2 3 5 8
}
}
如果是字符串类型的List,OrderBy会按照字符串的字典序进行升序排列,示例如下:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<string> strList = new List<string> { "banana", "apple", "cherry", "date" };
var sortedStrList = strList.OrderBy(str => str).ToList();
Console.WriteLine("字符串升序排序结果:");
foreach (var str in sortedStrList)
{
Console.Write(str + " ");
}
// 输出结果:apple banana cherry date
}
}
自定义对象List的升序排序
实际开发中我们更多会处理自定义对象的List,这时候需要在OrderBy的委托中指定具体的排序属性。比如我们有一个学生类,需要按照学生的分数进行升序排列:
using System;
using System.Collections.Generic;
using System.Linq;
// 定义学生类
public class Student
{
public string Name { get; set; }
public int Score { get; set; }
}
class Program
{
static void Main()
{
// 初始化学生List
List<Student> studentList = new List<Student>
{
new Student { Name = "张三", Score = 85 },
new Student { Name = "李四", Score = 72 },
new Student { Name = "王五", Score = 93 },
new Student { Name = "赵六", Score = 68 }
};
// 按照Score属性升序排序
var sortedStudents = studentList.OrderBy(stu => stu.Score).ToList();
Console.WriteLine("按分数升序排序的学生列表:");
foreach (var stu in sortedStudents)
{
Console.WriteLine($"姓名:{stu.Name},分数:{stu.Score}");
}
}
}
上面的代码中,stu => stu.Score就是指定了按照Student对象的Score属性作为排序键,最终得到的集合会按照分数从低到高排列。
OrderBy和其他排序方式的对比
除了OrderBy,C#中还有Sort方法可以实现List排序,两者的区别如下:
| 对比项 | OrderBy | List.Sort |
|---|---|---|
| 是否修改原集合 | 否,返回新序列 | 是,直接修改原集合 |
| 排序方向默认 | 升序 | 升序(可传自定义比较器) |
| 使用复杂度 | 简单,无需自定义比较逻辑 | 复杂对象排序可能需要自定义比较器 |
使用OrderBy的注意事项
- 使用OrderBy前需要引入System.Linq命名空间,否则会提示方法不存在。
- OrderBy返回的是IEnumerable类型,如果需要List类型的结果,需要调用ToList方法转换。
- 如果需要降序排列,可以使用OrderByDescending方法,使用方式和OrderBy一致。
- 如果需要多条件排序,可以在OrderBy之后使用ThenBy方法指定次要排序条件,比如先按分数升序,分数相同再按姓名升序,示例如下:
var multiSorted = studentList.OrderBy(stu => stu.Score).ThenBy(stu => stu.Name).ToList();