// 创建一个包">

c#list怎么排序

来源:这里教程网 时间:2026-02-21 16:48:23 作者:

如何对 C# List 进行排序

在 C# 中,可以使用各种方法对 List 集合进行排序。最常见的方法是使用内置的 Sort() 方法和 LINQ 语句。

使用 Sort() 方法

Sort() 方法使用快速排序算法对列表中的元素进行排序,该算法具有平均时间复杂度为 O(n log n)。该方法适用于已实现 IComparable 接口的类型。

<code class="csharp">// 创建一个包含整型的 List
List<int> numbers = new List<int> { 5, 1, 9, 2, 4 };
// 使用 Sort() 方法对列表进行排序
numbers.Sort();
// 打印排序后的列表
foreach (int number in numbers)
{
    Console.WriteLine(number);
}</code>

输出:

<code>1
2
4
5
9</code>

使用 LINQ 语句

LINQ(语言集成查询)提供了一种使用 Lambda 表达式查询和操作集合的简洁方法。可以使用 OrderBy() 和 OrderByDescending() 运算符对 List 进行排序。

<code class="csharp">// 创建一个包含字符串的 List
List<string> fruits = new List<string> { "Apple", "Banana", "Orange", "Mango" };
// 使用 LINQ 语句对列表按升序排序
var sortedAsc = fruits.OrderBy(f => f);
// 使用 LINQ 语句对列表按降序排序
var sortedDesc = fruits.OrderByDescending(f => f);</code>

sortedAsc 和 sortedDesc 是排序后的 IEnumerable 集合,可以使用 foreach 循环将其打印出来。

相关推荐