自定义Sort函数排序规则

版权声明:欢迎大家留言讨论共同进步,转载请注明出处 https://blog.csdn.net/qq_39108767/article/details/83448052

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;
        }
    }

}

猜你喜欢

转载自blog.csdn.net/qq_39108767/article/details/83448052