c# list的sort怎么按条件排序

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

C# List 按条件排序

在 C# 中,List 的 Sort 方法提供了一种根据指定条件对 List 中元素进行排序的方法。

按条件排序步骤

要使用 Sort 方法按条件排序 List,请遵循以下步骤:

    定义比较器:创建一个 IComparer 接口的实现,它定义了比较两个元素并返回排序顺序(升序或降序)的规则。 提供排序键:在比较器中,指定用于比较元素的属性或字段。 调用 Sort 方法:使用 Sort 方法,将比较器作为参数传递,对 List 进行排序。

示例代码

以下代码示例演示了如何按字符串长度对 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 或 IComparer 进行比较 日期和时间:使用 IComparer 进行比较 布尔值:使用 IComparer 进行比较 枚举类型:使用 IComparer 进行比较,其中 T 是枚举类型的基础类型

相关推荐