天天看點

unity3dC#的List升序降序排序

List.Sort有三種結果 1,-1,0分别是大,小,相等

升序降序比較,預設List的排序是升序排序

如果要降序排序,也很簡單,隻需要在前面加一個負号

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

對于非數值類型比較用.CompareTo(...),基于IComparable接口。基本上C#的值類型都有實作這個接口,包括string。

而數值類型也可以自己比較。排序時左右兩個變量必須是左-比較-右,切記不可反過來比較。

sort方法官方推薦的 命名方式是x(左),y(右) 。對于複雜的比較 可以分出來,單獨寫成函數

多權重比較

假設需要tuple裡item2的值優先于item1。這個時候隻要給比較結果*2即可。

List<Tuple<int, int>> tmp = new List<Tuple<int, int>>()
{
    new Tuple<int,int>(2,1),
    new Tuple<int,int>(53,1),
    new Tuple<int,int>(12,1),
    new Tuple<int,int>(22,3),
    new Tuple<int,int>(1,2),
};
tmp.Sort((x, y) => -(x.Item1.CompareTo(y.Item1) + x.Item2.CompareTo(y.Item2) * 2));
Console.WriteLine(tmp);
//22,3
//1,2
//53,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))
        {
            // 蘭姆達表達式,等級排序
            // 升序
            myList.Sort((x, y) => { return x.level.CompareTo(y.level); });
            // 降序
            myList.Sort((x, y) => { return -x.level.CompareTo(y.level); });
        }

    }
}