C# List.Where()
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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!