Unity的List排序

       Unity的List.Sort有三種結果 1,-1,0分別是大,小,相等。默認List的排序是升序排序,如果要降序排序,也很簡單,只需要在前面加一個負號即可。

List<int> m_temp = new List<int>(){6,1,3,5,4};
//  升序
m_temp.Sort((x, y) => x.CompareTo(y));
// 降序
m_temp.Sort((x, y) => -x.CompareTo(y));
Console.WriteLine(m_temp);
// 6,5,4,3,1

       對於非數值類型比較用.CompareTo(...),基於IComparable接口。基本上C#的值類型都有實現這個接口,包括string。而數值型也可以自己比較。排序時左右兩個變量必須是左-比較-右,切記不可反過來比較。sort方法官方推薦的 命名方式是x(左),y(右) 。對於複雜的比較 可以分出來,單獨寫成函數。多權重比較,假設需要tuple裏item2的值優先於item1。這個時候只要給比較結果*2即可。

List<Tuple<int, int>> m_temp = new List<Tuple<int, int>>()
{
    new Tuple<int,int>(2,1),
    new Tuple<int,int>(43,1),
    new Tuple<int,int>(12,1),
    new Tuple<int,int>(33,5),
    new Tuple<int,int>(1,4),
};
m_temp.Sort((x, y) => -(x.Item1.CompareTo(y.Item1) + x.Item2.CompareTo(y.Item2) * 2));
Console.WriteLine(m_temp);
//33,5
//1,4
//43,1
//12,1
//2,1

// List按照指定字段進行排序

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

public class Test : MonoBehaviour
{
    public class MyInfo
    {
        public MyInfo(string name, int level, int age)
        {
            this.name = name;
            this.level = level;
            this.age = age;
        }
        public string name;
        public int level;
        public int age;
    }
    public List<MyInfo> myList = new List<MyInfo>();
    void Awake()
    {
        myList.Add(new MyInfo("A", 2, 9));
        myList.Add(new MyInfo("C", 8, 6));
        myList.Add(new MyInfo("B", 6, 7));
    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            // lambda表達式,等級排序
            // 升序
            myList.Sort((x, y) => { return x.level.CompareTo(y.level); });
            // 降序
            myList.Sort((x, y) => { return -x.level.CompareTo(y.level); });
        }

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章