【100个 Unity实用技能】☀️ | C# 中 Sort() 对List中的数据排序的几种方法 整理总结

本文介绍了Unity及其实用小技能。Unity是实时3D互动内容创作和运营平台,可用于多领域创作。重点讲解了C#中对List数据排序的方法,包括对值类型直接用Sort()方法排序,以及对自定义类型通过继承接口、定义委托方法等方式实现排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

请添加图片描述

Unity 小科普

老规矩,先介绍一下 Unity 的科普小知识:

  • Unity是 实时3D互动内容创作和运营平台 。
  • 包括游戏开发美术建筑汽车设计影视在内的所有创作者,借助 Unity 将创意变成现实。
  • Unity 平台提供一整套完善的软件解决方案,可用于创作、运营和变现任何实时互动的2D和3D内容,支持平台包括手机平板电脑PC游戏主机增强现实虚拟现实设备。
  • 也可以简单把 Unity 理解为一个游戏引擎,可以用来专业制作游戏
  • 🎬 博客主页:https://xiaoy.blog.youkuaiyun.com

  • 🎥 本文由 呆呆敲代码的小Y 原创,首发于 优快云🙉

  • 🎄 学习专栏推荐:Unity系统学习专栏

  • 🌲 游戏制作专栏推荐:游戏制作

  • 🌲Unity实战100例专栏推荐:Unity 实战100例 教程

  • 🏅 欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请指正!

  • 📆 未来很长,值得我们全力奔赴更美好的生活✨

  • ------------------❤️分割线❤️-------------------------

请添加图片描述


Unity 实用小技能学习

C#对List中的数据排序的几种方法

在C#中我们会经常用到List<>作为一个容器使用,在使用的过程中往往要对集合中的数据进行排序操作。

本文就来介绍一些好用的排序方法,一起来看看吧!

一、对 值类型 进行排序直接使用 Sort()方法

直接使用 C# 中的成员方法 Sort() 可以对C#本身的几种类型进行排序,比如 int,float,double 等。

Sort() 有四种重载如下:

        public void Sort(Comparison<T> comparison);
        public void Sort(int index, int count, IComparer<T> comparer);
        public void Sort();
        public void Sort(IComparer<T> comparer);

具体示例:

	//申明一个List容器
	List<int> list = new List<int>();
	//向list中添加数据
	list.Add(999);
	list.Add(666);
	list.Add(888);
	//排序
	list.Sort();

在这里插入图片描述

值得一提的是,直接使用 Sort() 对List也可以排序,默认的排序规则是按照ASCII码进行的。

在这里插入图片描述

二、对自定义类型进行排序

首先声明一个自定义类型

    class Student
    {
        public string name;
        public int age;
        public Student(string name,int age)
        {
            this.name = name;
            this.age = age;
        }
    }

声明一个自定义类型的List

        List<Student> studentList = new List<Student>();
        studentList.Add(new Student("小Y",20));
        studentList.Add(new Student("小小Y", 10));
        studentList.Add(new Student("Y", 30));
        
        //studentList.Sort();//会报错

此时直接使用studentList.sort()是报错的:ArgumentException:至少一个对象必须实现IComparable。

在这里插入图片描述
下面就来介绍几种可以自定义类型排序的几种方法

1. 继承接口IComparable<>

将自定义类型继承 接口IComparable<> ,并实现接口成员CompareTo

按照年龄进行排序,代码如下:

    class Student:IComparable<Student>
    {
        public string name;
        public int age;
        public Student(string name,int age)
        {
            this.name = name;
            this.age = age;
        }
        public int CompareTo(Student other)
        {
            //返回值含义:
            //小于0:放在传入对象的前面
            //等于0:保持当前的位置不变
            //大于0:放在传入对象的后面
            if (this.age > other.age) return 1;
            else return -1;
        }
    }

此时声明一个自定义类型的List,并进行排序,就可以正常排序成功啦!

        List<Student> studentList = new List<Student>();
        studentList.Add(new Student("小Y",20));
        studentList.Add(new Student("小小Y", 10));
        studentList.Add(new Student("Y", 30));
        studentList.Sort();

        foreach (var l in studentList)
        {
            Debug.Log("name:"+l.name+",age:"+ l.age);
        }

在这里插入图片描述

2. 定义一个委托方法进行排序

Sort() 有一种重载参数是一个返回值为int类型的委托类型,可以在外面声明一个用来排序的方法。

代码如下:

    class Student
    {
        public string name;
        public int age;
        public Student(string name,int age)
        {
            this.name = name;
            this.age = age;
        }
    }
    
    void Start()
    {
        List<Student> studentList = new List<Student>();
        studentList.Add(new Student("小Y",20));
        studentList.Add(new Student("小小Y", 10));
        studentList.Add(new Student("Y", 30));
        studentList.Sort(SortItem);//将方法名作为参数传递,实现排序
    }
    
    private int SortItem(Student stu1, Student stu2)
    {
        //传入的对象为列表中的对象
        //进行两两比较,用左边的和右边的 按条件 比较
        //返回值规则与接口方法相同
        if (stu1.age > stu2.age) return 1;
        else return -1;
    }

上述代码也可以使用 Lambda表达式 直接排序,代码如下:

        List<Student> studentList = new List<Student>();
        studentList.Add(new Student("小Y",20));
        studentList.Add(new Student("小小Y", 10));
        studentList.Add(new Student("Y", 30));

        studentList.Sort((stu1, stu2) => { return stu1.age > stu2.age ? 1 : -1; });

3.若自定义类型中有多个数值都要参与到排序规则中,可自定义排序类型先后

    class Student
    {
        public string name;
        public int age;
        public int score;
        public Student(string name,int age,int score)
        {
            this.name = name;
            this.age = age;
            this.score = score;
        }

        public static int Sort(Student a, Student b)
        {
            if (a.score > b.score)
            {
                // -1表示将a排在b前面
                return -1;
            }
            else if (a.score == b.score)//若分数相同时,再按照年龄进行排序
            {
                if (a.age > b.age)
                {
                    return -1;
                }
                else if (b.age > a.age)
                {
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
            else
            {
                return 1;
            }
        }
    }
    void Start()
    {
        List<Student> studentList = new List<Student>();
        studentList.Add(new Student("小Y", 20, 90));
        studentList.Add(new Student("小小Y", 20, 80));
        studentList.Add(new Student("Y", 30, 90));
        studentList.Sort(Student.Sort);

        foreach (var l in studentList)
        {
            Debug.Log("name:" + l.name + ",age:" + l.age + ",score:" + l.score);
        }
    }

在这里插入图片描述

上述几种排序方法中 一般使用 委托方法的Lambda表达式 就可以满足我们大部分的排序需求了!

 list.Sort((item1, item2) => { return item1.age > item2.age ? 1 : -1; });

在这里插入图片描述

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆呆敲代码的小Y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值