List.Where():找出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 //提取所有年纪在22和25之间的学生 16 foreach (var student in ExtractStudentsAgedBetween22And25()) 17 { 18 Debug.Log(student.ToString()); 19 } 20 } 21 22 #region 提取所有年纪在22和25之间的学生 23 24 /*//错误写法:无法将List<Student>隐式转换为List<dynamic> 25 List<dynamic> ExtractAllStudentId() 26 { 27 List<dynamic> tempStudents = students.Where( 28 t => t.age > 22 && t.age < 25 29 ).ToList(); 30 31 return tempStudents; 32 }*/ 33 34 //正确写法 35 List<Student> ExtractStudentsAgedBetween22And25() 36 { 37 List<Student> tempStudents = students.Where( 38 t => t.age > 22 && t.age < 25 39 ).ToList(); 40 41 return tempStudents; 42 } 43 #endregion 44 } 45 /// <summary> 46 /// 学生信息 47 /// </summary> 48 [System.Serializable] 49 public class Student 50 { 51 /// <summary> 52 /// 名字 53 /// </summary> 54 public string name; 55 /// <summary> 56 /// 年龄 57 /// </summary> 58 public int age; 59 /// <summary> 60 /// 学号 61 /// </summary> 62 public int id; 63 /// <summary> 64 /// 性别 65 /// </summary> 66 public Gender gender; 67 68 public override string ToString() 69 { 70 return string.Format("{0},{1},{2},{3}", name, age, id, gender == Gender.Female ? "女" : "男"); 71 } 72 } 73 /// <summary> 74 /// 性别 75 /// </summary> 76 public enum Gender 77 { 78 /// <summary> 79 /// 女性 80 /// </summary> 81 Female, 82 /// <summary> 83 /// 男性 84 /// </summary> 85 Male, 86 }View Code 标签:25,22,C#,age,List,Where,public From: https://www.cnblogs.com/Peng18233754457/p/18043050