C# List 按条件排序
在 C# 中,List 的 Sort 方法提供了一种根据指定条件对 List 中元素进行排序的方法。
按条件排序步骤
要使用 Sort 方法按条件排序 List,请遵循以下步骤:
-
定义比较器:创建一个 IComparer
示例代码
以下代码示例演示了如何按字符串长度对 List
<code class="csharp">using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 定义一个字符串列表
List<string> names = new List<string>() { "John", "Alice", "Bob", "Emily" };
// 定义字符串长度比较器
class StringLengthComparer : IComparer<string>
{
public int Compare(string x, string y)
{
// 根据字符串长度比较两个字符串
return x.Length.CompareTo(y.Length);
}
}
// 按字符串长度对列表排序
names.Sort(new StringLengthComparer());
// 输出排序后的列表
foreach (string name in names)
{
Console.WriteLine(name);
}
}
}</code>其他条件排序示例
除了字符串长度,你还可以按其他条件对 List 进行排序,例如:
数值:使用 IComparer