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));   // 简单乱序
相关推荐
小码编匠3 小时前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫2 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech2 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf4 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6254 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech4 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
LDR0065 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术5 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
码云数智-园园5 天前
C++20 Modules 模块详解
java·开发语言·spring
swordbob5 天前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio