C# 中对 List 中的值重新排序有两种常用方法:使用 Sort() 方法进行就地排序,指定比较规则。使用 OrderBy() 和 ThenBy() 查询表达式进行排序,指定主要和次要排序规则。

如何对 C# 中 List 中的值重新排序
在 C# 中,可以通过多种方式对 List 中的值进行重新排序。以下是两种最常用的方法:
1. 使用 Sort() 方法
Sort() 方法根据指定的比较规则对 List 中的元素进行就地排序。语法如下:
<code class="csharp">list.Sort();</code>
对于自定义类,可以使用 IComparer<T> 或 IComparable<T> 接口来指定比较规则。
2. 使用 OrderBy() 和 ThenBy() 查询表达式
OrderBy() 和 ThenBy() 查询表达式使用委托语法对 List 中的元素进行排序。语法如下:
<code class="csharp">var sortedList = list.OrderBy(x => x.Property).ThenBy(x => x.AnotherProperty);</code>
OrderBy() 指定主要排序规则,ThenBy() 指定次要排序规则。
示例
以下示例演示了如何使用 Sort() 方法和 OrderBy() 查询表达式对 List 中的整数进行排序:
<code class="csharp">// 使用 Sort() 方法
List<int> numbers = new List<int> { 5, 1, 3, 2, 4 };
numbers.Sort();
// 输出排序后的列表
Console.WriteLine("使用 Sort() 方法排序:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
// 使用 OrderBy() 查询表达式
var sortedNumbers = numbers.OrderBy(x => x);
// 输出排序后的列表
Console.WriteLine("使用 OrderBy() 查询表达式排序:");
foreach (int number in sortedNumbers)
{
Console.WriteLine(number);
}</code>输出:
<code>使用 Sort() 方法排序: 1 2 3 4 5 使用 OrderBy() 查询表达式排序: 1 2 3 4 5</code>
以上就是c#怎么对list里面的值重新排序的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号