方法和效果
有多个排序条件,其实不用单独自己写排序方法的,C#内置了排序方法:
引用命名空间System.Linq
正向排序的方法:OrderBy首要条件;ThenBy次要条件,可以连续多个使用
同理,逆向排序对应的方法是OrderByDescending、ThenByDescending
正向排序和逆向排序可以交叉使用
完整代码
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;public class Test01 : MonoBehaviour
{public class student{public int id { get; set; }public string name { get; set; }public string hometown { get; set; }public student(int id, string name, string hometown){this.id = id;this.name = name;this.hometown = hometown;}public override string ToString(){return $"{this.id} {this.name} {this.hometown}";}}// Start is called before the first frame updateList<student> list = new List<student>(){new student(1, "1", "3"),new student(1, "1", "2"),new student(1, "2", "1"),new student(2, "2", "2"),new student(3, "2", "1"),new student(2, "3", "1"),new student(1, "3", "3"),};void PrintList(){foreach (var VARIABLE in list){Debug.Log(VARIABLE.ToString());}Debug.LogWarning("--------------------------");}void Start(){PrintList();}// Update is called once per framevoid Update(){if (Input.GetKeyDown(KeyCode.A)){//依次安装id,name,hometown正向排序list = list.OrderBy(x => x.id).ThenBy(x => x.name).ThenBy(x => x.hometown).ToList();;PrintList();}if (Input.GetKeyDown(KeyCode.S)){//依次安装id,name,hometown反向排序list = list.OrderByDescending(x => x.id).ThenByDescending(x => x.name).ThenByDescending(x => x.hometown).ToList();;PrintList();}}
}
参考连接
Queryable.ThenBy Method (System.Linq) | Microsoft Learn