自定义Sort函数排序规则_024

发表于2018-09-27
评论0 1k浏览
sort()函数默认是升序排序,但这里要和大家分享的是自定义Sort函数排序规则,方便大家去选择适合自己项目的排序。

代码实现:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
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;
    }
}
关于自定义Sort函数排序规则就分享这么多,希望能帮到各位。

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引

标签: