1. 程式人生 > >自定義Sort函式排序規則

自定義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;
        }
    }

}