c# list 排序
时间: 2024-02-02 15:10:11 浏览: 39
以下是C#中List排序的三种方法:
1. 使用Sort()方法进行升序排序:
```csharp
List<int> numbers = new List<int> {7, 4, 5, 3, 8};
numbers.Sort();
```
2. 使用Comparison委托进行自定义排序:
```csharp
List<int> numbers = new List<int> {7, 4, 5, 3, 8};
numbers.Sort((a, b) => a.CompareTo(b));
```
3. 使用OrderBy和ThenBy方法进行多条件排序:
```csharp
List<int> numbers = new List<int> {7, 4, 5, 3, 8};
var sortedNumbers = numbers.OrderBy(x => x).ThenBy(x => x);
```
倒序排序可以使用Reverse()方法对已排序的列表进行反转:
```csharp
List<int> numbers = new List<int> {7, 4, 5, 3, 8};
numbers.Sort();
numbers.Reverse();
```
相关问题
C# list 排序
在 C# 中,可以使用 List<T> 类型的 Sort() 方法对列表进行排序。以下是一个示例代码:
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int>() { 5, 2, 9, 1, 3 };
numbers.Sort();
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
```
这个示例将会输出已排序的数字列表:
```
1
2
3
5
9
```
你也可以使用 List<T> 类型的 Sort() 方法的重载版本,传入一个自定义的比较器来实现自定义排序规则。例如,你可以使用 Comparison<T> 委托来指定排序规则:
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> names = new List<string>() { "John", "Alice", "Bob" };
names.Sort((x, y) => x.Length.CompareTo(y.Length));
foreach (string name in names)
{
Console.WriteLine(name);
}
}
}
```
这个示例将会按照字符串长度进行排序:
```
Bob
John
Alice
```
希望这可以帮助到你!如有任何疑问,请随时提问。
C# list<> 排序
C#的List<>类提供了Sort()方法用于对列表进行排序。Sort()方法可以接受一个可选的比较器参数,以便根据自定义排序规则进行排序。
以下是一个示例,展示如何对List<>进行排序:
```csharp
List<int> numbers = new List<int> { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5 };
// 排序并输出结果
numbers.Sort();
foreach (var num in numbers)
{
Console.Write(num + " ");
}
Console.WriteLine();
// 使用自定义比较器排序并输出结果
numbers.Sort(new MyComparer());
foreach (var num in numbers)
{
Console.Write(num + " ");
}
Console.WriteLine();
// 自定义比较器实现
public class MyComparer : IComparer<int>
{
public int Compare(int x, int y)
{
if (x < y)
{
return -1;
}
else if (x > y)
{
return 1;
}
else
{
return 0;
}
}
}
```
在上面的示例中,我们首先创建一个包含一些整数的List<>,然后调用Sort()方法对其进行排序。默认情况下,Sort()方法使用默认比较器对列表进行排序。
接下来,我们定义了一个自定义比较器类MyComparer,并将其作为参数传递给Sort()方法,以便按照自定义的排序规则进行排序。在这个例子中,我们只是简单地比较了两个整数的大小,从而实现了升序排序。
相关推荐
![](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)