20250606-C#知识:List排序

C#知识:List排序

默认排序往往不够用,学会自定义排序很重要。


1、默认排序

  • 只有少数类型能用,例如值类型int、float,double等
  • 默认升序
csharp 复制代码
//系统自带排序
List<int> list = new();
list.Add(5);
list.Add(8);
list.Add(1);
list.Add(6);
list.Add(2);
Print<int>(list);   //5 8 1 6 2
//系统默认排序方法,默认升序
list.Sort();
Print<int>(list);   //1 2 5 6 8

2、实现IComparable接口

  • 重写CompareTo方法,实现排序逻辑
csharp 复制代码
class Equipment:IComparable<Equipment>
{
    public string equipmentName;
    public int damage;
    public float price;

    public Equipment(string equipmentName, int damage, float price)
    {
        this.equipmentName = equipmentName;
        this.damage = damage;
        this.price = price;
    }

    public int CompareTo(Equipment? other)
    {
        if(this.price > other.price)
            return -1;
        else if(this.price < other.price)
            return 1;
        return 0;
    }

    public override string ToString()
    {
        return $" 【名称:{equipmentName}, 伤害:{damage}, 价格:{price}】";
    }
}
csharp 复制代码
List<Equipment> equipments = new List<Equipment>();
equipments.Add(new Equipment("猎犬长牙", 58, 100));
equipments.Add(new Equipment("碎星大剑", 120, 500));
equipments.Add(new Equipment("陨石杖", 60, 300));
equipments.Add(new Equipment("黄铜盾", 0, 200));
//以实现接口方式:价格降序排序
equipments.Sort();  //不实现接口直接排序会报错Unhandled exception. System.InvalidOperationException: Failed to compare two elements in the array.
Print<Equipment>(equipments);//【名称:碎星大剑, 伤害:120, 价格:500】  【名称:陨石杖, 伤害:60, 价格:300】  【名称:黄铜盾, 伤害:0, 价格:200】  【名称:猎犬长牙, 伤害:58, 价格:100】

3、传递委托函数

  • 直接Sort方法传入委托函数参数
csharp 复制代码
//Sort传入委托函数
//伤害升序
equipments.Sort((a, b) =>
{
    if (a.damage > b.damage)
        return 1;
    else if (a.damage < b.damage)
        return -1;
    return 0;
});
Print<Equipment>(equipments);//【名称:黄铜盾, 伤害:0, 价格:200】  【名称:猎犬长牙, 伤害:58, 价格:100】  【名称:陨石杖, 伤害:60, 价格:300】  【名称:碎星大剑, 伤害:120, 价格:500】

4、完整代码示例

csharp 复制代码
namespace LearnListSort
{
    class Equipment:IComparable<Equipment>
    {
        public string equipmentName;
        public int damage;
        public float price;

        public Equipment(string equipmentName, int damage, float price)
        {
            this.equipmentName = equipmentName;
            this.damage = damage;
            this.price = price;
        }

        public int CompareTo(Equipment? other)
        {
            if(this.price > other.price)
                return -1;
            else if(this.price < other.price)
                return 1;
            return 0;
        }

        public override string ToString()
        {
            return $" 【名称:{equipmentName}, 伤害:{damage}, 价格:{price}】";
        }
    }
    
    internal class Program
    {
        static void Print<T>(List<T> list)
        {
            foreach (T item in list)
            {
                Console.Write(item.ToString() + " ");
            }
            Console.WriteLine();
        }
        static void Main(string[] args)
        {
            //系统自带排序
            List<int> list = new();
            list.Add(5);
            list.Add(8);
            list.Add(1);
            list.Add(6);
            list.Add(2);
            Print<int>(list);   //5 8 1 6 2
            //系统默认排序方法,默认升序
            list.Sort();
            Print<int>(list);   //1 2 5 6 8

            List<Equipment> equipments = new List<Equipment>();
            equipments.Add(new Equipment("猎犬长牙", 58, 100));
            equipments.Add(new Equipment("碎星大剑", 120, 500));
            equipments.Add(new Equipment("陨石杖", 60, 300));
            equipments.Add(new Equipment("黄铜盾", 0, 200));
            //以实现接口方式:价格降序排序
            equipments.Sort();  //不实现接口直接排序会报错Unhandled exception. System.InvalidOperationException: Failed to compare two elements in the array.
            Print<Equipment>(equipments);//【名称:碎星大剑, 伤害:120, 价格:500】  【名称:陨石杖, 伤害:60, 价格:300】  【名称:黄铜盾, 伤害:0, 价格:200】  【名称:猎犬长牙, 伤害:58, 价格:100】
            //Sort传入委托函数
            //伤害升序
            equipments.Sort((a, b) =>
            {
                if (a.damage > b.damage)
                    return 1;
                else if (a.damage < b.damage)
                    return -1;
                return 0;
            });
            Print<Equipment>(equipments);//【名称:黄铜盾, 伤害:0, 价格:200】  【名称:猎犬长牙, 伤害:58, 价格:100】  【名称:陨石杖, 伤害:60, 价格:300】  【名称:碎星大剑, 伤害:120, 价格:500】
        }
    }
}

5、参考资料

  1. 《唐老狮C#》

本文结束,感谢您的阅读~

相关推荐
CoderIsArt4 小时前
C#中的CLR属性、依赖属性与附加属性
c#
IGP99 小时前
20250606-C#知识:委托和事件
开发语言·c#
Kookoos10 小时前
ABP VNext 与 Neo4j:构建基于图数据库的高效关系查询
数据库·c#·.net·neo4j·abp vnext
张鱼小丸子_微辣11 小时前
.Net Framework 4/C# LINQ*
c#
..活宝..12 小时前
【Emgu CV教程】11.2、Scharr边缘检测
图像处理·计算机视觉·c#·emgu cv·图像分析
yngsqq12 小时前
事件监听 ——CAD C#二次开发
c#
The Kite13 小时前
MPLAB X IDE 软件安装与卸载
ide·c#·嵌入式
qq_4335545415 小时前
C++ list代码练习、set基础概念、set对象创建、set大小操作
开发语言·c++·list
张鱼小丸子_微辣16 小时前
.Net Framework 4/C# 集合和索引器
c#
布伦鸽16 小时前
C# WPF 左右布局实现学习笔记(1)
笔记·学习·c#·wpf