List.Sort():对List所有元素按条件进行排序。
1 using System.Collections; 2 using System.Collections.Generic; 3 using System.Linq; 4 using UnityEngine; 5 6 public class Test : MonoBehaviour 7 { 8 /// <summary> 9 /// 所有学生 10 /// </summary> 11 public List<Student> students = new List<Student>(); 12 13 private void Start() 14 { 15 //根据年纪从大到小重新排序 16 SortOldToYoung(); 17 foreach (var student in students) 18 { 19 Debug.Log(student.ToString()); 20 } 21 } 22 /// <summary> 23 /// 根据年纪从大到小重新排序 24 /// </summary> 25 void SortOldToYoung() 26 { 27 //写法1 28 /*students.Sort((x, y) => 29 { 30 return (y.age - x.age); 31 });*/ 32 33 //写法2 34 students.Sort((x, y) => (y.age - x.age)); 35 36 //写法3 37 //students.Sort((x, y) => y.age > x.age ? 0 : -1); 38 } 39 } 40 /// <summary> 41 /// 学生信息 42 /// </summary> 43 [System.Serializable] 44 public class Student 45 { 46 /// <summary> 47 /// 名字 48 /// </summary> 49 public string name; 50 /// <summary> 51 /// 年龄 52 /// </summary> 53 public int age; 54 /// <summary> 55 /// 学号 56 /// </summary> 57 public int id; 58 /// <summary> 59 /// 性别 60 /// </summary> 61 public Gender gender; 62 63 public override string ToString() 64 { 65 return string.Format("{0},{1},{2},{3}", name, age, id, gender == Gender.Female ? "女" : "男"); 66 } 67 } 68 /// <summary> 69 /// 性别 70 /// </summary> 71 public enum Gender 72 { 73 /// <summary> 74 /// 女性 75 /// </summary> 76 Female, 77 /// <summary> 78 /// 男性 79 /// </summary> 80 Male, 81 }View Code 标签:Sort,C#,age,List,students,using,public From: https://www.cnblogs.com/Peng18233754457/p/18043126