在c#编程中,对list里面的值重新排序是最常见的数据处理需求之一。根据数据类型和排序规则的不同,我们可以选择不同的实现方式,既可以使用List类自带的Sort方法,也可以借助LINQ提供的OrderBy等扩展方法。

使用List的Sort方法
List<T>本身提供了Sort方法,可以直接对集合进行原地排序。对于基础类型如int、string,默认会按照从小到大或从字母顺序排。
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> nums = new List<int> { 5, 2, 8, 1, 3 };
// 默认升序排序
nums.Sort();
foreach (int n in nums)
{
Console.WriteLine(n);
}
}
}
使用自定义比较器降序
如果需要降序,可以传入Comparison委托或者使用Reverse方法。
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> nums = new List<int> { 5, 2, 8, 1, 3 };
// 使用Comparison进行降序
nums.Sort((a, b) => b.CompareTo(a));
foreach (int n in nums)
{
Console.WriteLine(n);
}
}
}
使用LINQ的OrderBy和OrderByDescending
LINQ方式不会修改原list,而是返回一个新的有序序列,适合函数式风格编码。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> nums = new List<int> { 5, 2, 8, 1, 3 };
// 升序
var asc = nums.OrderBy(x => x).ToList();
// 降序
var desc = nums.OrderByDescending(x => x).ToList();
asc.ForEach(x => Console.Write(x + " "));
Console.WriteLine();
desc.ForEach(x => Console.Write(x + " "));
}
}
对对象列表按属性排序
当list中存放的是自定义对象时,可以指定属性作为排序键。
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 = "Tom", Score = 80 },
new Student { Name = "Amy", Score = 95 },
new Student { Name = "Bob", Score = 70 }
};
// 按分数升序
var sorted = students.OrderBy(s => s.Score).ToList();
sorted.ForEach(s => Console.WriteLine(s.Name + ":" + s.Score));
}
}
多条件排序
使用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 = "Tom", Score = 80 },
new Student { Name = "Amy", Score = 80 },
new Student { Name = "Bob", Score = 70 }
};
// 先按分数降序,再按名字升序
var sorted = students
.OrderByDescending(s => s.Score)
.ThenBy(s => s.Name)
.ToList();
sorted.ForEach(s => Console.WriteLine(s.Name + ":" + s.Score));
}
}
方法对比
| 方式 | 是否修改原list | 适用场景 |
|---|---|---|
| Sort方法 | 是 | 原地排序、性能敏感 |
| OrderBy | 否 | 链式查询、只读排序 |
| 自定义比较器 | 视调用方式 | 复杂对象排序 |
在实际项目中,如果只是简单调整顺序且不在意原集合变化,用Sort更直观;若需要保持原数据不变并组合其他查询,LINQ的OrderBy是更优选择。