【C#】自定义Sort函数排序规则

sort()函数默认是升序排序,只能应用于C#指定数据类型,但这里要和大家分享的是自定义Sort函数排序的对象和规则,方便大家去选择适合自己项目的排序。

代码实现:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Demo024
{
    public class SortCompare : MonoBehaviour
    {

        void Start()
        {
            List<People> list = new List<People>();

            for (int i = 0; i < 10; i++)
            {
                list.Add(new People("Name_" + i, 20 - i));
            }

            //方法一
            //如果People类没有继承IComparable接口,直接调用无参数的Sort()会报错
            //(int等部分数据类型可以直接调用该无参方法,因为其已经继承了IComparable接口)
            //只有List中的元素继承IComparable<>接口,且实现CompareTo()方法,在CompareTo()实现对象的比较规则。
            list.Sort();

            //方法二
            //定义一个比较规则类,该类继承IComparer<>接口,且实现Compare()方法,在Compare()实现对象的比较规则。
            list.Sort(new PeopleCompare());

            //设定比较的起点与长度
            list.Sort(0, 5, new PeopleCompare());

            //方法三
            //通过委托定义比较规则
            list.Sort((x, y) =>
            {
                if (x.age > y.age)
                    return 1;
                else if (x.age == y.age)
                    return 0;
                else
                    return -1;
            });

        }

    }

    public class People : IComparable<People>
    {
        public People(string n, int a)
        {
            name = n;
            age = a;
        }
        public string name;
        public int age;

        public int CompareTo(People other)
        {
            //返回值:1 -> 大于、 0 -> 等于、 -1 -> 小于
            if (age > other.age)
                return 1;
            else if (age == other.age)
                return 0;
            else
                return -1;
        }
    }

    public class PeopleCompare : IComparer<People>
    {
        public int Compare(People x, People y)
        {
            if (x.age > y.age)
                return 1;
            else if (x.age == y.age)
                return 0;
            else
                return -1;
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

萧然CS

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

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

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

打赏作者

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

抵扣说明:

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

余额充值