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));   // 简单乱序
相关推荐
Scout-leaf3 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530143 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools4 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的4 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21884 天前
.NET 本地Db数据库-技术方案选型
windows·c#
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
lindexi4 天前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言