OrderBy和OrderByDescending
时间: 2024-06-14 22:07:02 浏览: 12
OrderBy和OrderByDescending是.NET(C#)中Linq查询操作符,用于对数据进行排序。
OrderBy按照指定的条件对数据进行升序排序,而OrderByDescending则按照指定的条件对数据进行降序排序。
下面是一个示例代码,演示了如何使用OrderBy和OrderByDescending对一个整数列表进行排序:
```csharp
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 5, 2, 8, 1, 9 };
// 使用OrderBy进行升序排序
var ascendingOrder = numbers.OrderBy(n => n);
Console.WriteLine("升序排序结果:");
foreach (var number in ascendingOrder)
{
Console.WriteLine(number);
}
// 使用OrderByDescending进行降序排序
var descendingOrder = numbers.OrderByDescending(n => n);
Console.WriteLine("降序排序结果:");
foreach (var number in descendingOrder)
{
Console.WriteLine(number);
}
}
}
```
输出结果为:
```
升序排序结果:
1
2
5
8
9
降序排序结果:
9
8
5
2
1
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)