C#中对于List的多种排序方式

在 C# 中给 List<AI> 排序,只要 明确排序规则(比如按某个字段、某几个字段、或外部规则),就能用下面几种常见写法。下面全部基于这个示例类:

cs 复制代码
public class AI
{
    public int  country;   // 国家编号
    public int  priority;  // 额外权重
    public float hp;       // 血量
}

1. 单字段排序(最常用)

cs 复制代码
// 升序
aiList.Sort((a, b) => a.country.CompareTo(b.country));

// 降序
aiList.Sort((a, b) => b.country.CompareTo(a.country));

// 或者 LINQ(返回新列表,原列表顺序不变)
var ordered = aiList.OrderBy(ai => ai.country).ToList();        // 升
var ordered = aiList.OrderByDescending(ai => ai.country).ToList(); // 降

2. 多字段排序(先按 country,再按 priority)

cs 复制代码
// 方法 A:Sort + 元组
aiList.Sort((a, b) =>
{
    int r = a.country.CompareTo(b.country);
    return r != 0 ? r : a.priority.CompareTo(b.priority);
});

// 方法 B:LINQ 链式
var ordered = aiList
    .OrderBy(ai => ai.country)
    .ThenByDescending(ai => ai.priority) // 第二个字段可升/降
    .ToList();

3. 实现 IComparable<AI>(类内自带规则)

cs 复制代码
public class AI : IComparable<AI>
{
    public int country;
    public int priority;

    public int CompareTo(AI other)
    {
        int r = country.CompareTo(other.country);
        return r != 0 ? r : priority.CompareTo(other.priority);
    }
}

// 使用
aiList.Sort();   // 直接按 CompareTo 规则排序

4. 自定义排序器(IComparer<AI>

当规则需要外部注入动态变化时使用:

cs 复制代码
public class CountryPriorityComparer : IComparer<AI>
{
    public int Compare(AI x, AI y)
    {
        int r = x.country.CompareTo(y.country);
        return r != 0 ? r : x.priority.CompareTo(y.priority);
    }
}

aiList.Sort(new CountryPriorityComparer());

5,随机/乱序排序(额外补充)

cs 复制代码
System.Random rng = new System.Random();
aiList.Sort((_, __) => rng.Next(-1, 2));   // 简单乱序
相关推荐
坐吃山猪20 小时前
SpringBoot01-配置文件
java·开发语言
晚风(●•σ )20 小时前
C++语言程序设计——06 字符串
开发语言·c++
我叫汪枫21 小时前
《Java餐厅的待客之道:BIO, NIO, AIO三种服务模式的进化》
java·开发语言·nio
Nicole-----21 小时前
Python - Union联合类型注解
开发语言·python
晚云与城21 小时前
今日分享:C++ -- list 容器
开发语言·c++
兰雪簪轩21 小时前
分布式通信平台测试报告
开发语言·网络·c++·网络协议·测试报告
FPGAI1 天前
Qt编程之信号与槽
开发语言·qt
Swift社区1 天前
从 JDK 1.8 切换到 JDK 21 时遇到 NoProviderFoundException 该如何解决?
java·开发语言
0wioiw01 天前
Go基础(④指针)
开发语言·后端·golang
almighty271 天前
C# WinForm分页控件实现与使用详解
c#·winform·分页控件·c#分页·winform分页