List.Find() :获取List中第一个符合条件的元素,并返回该元素;
List.FindAll() :获取List中所有符合条件的元素,并最终返回一个列表。
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public class Test : MonoBehaviour 6 { 7 /// <summary> 8 /// 所有学生 9 /// </summary> 10 public List<Student> students = new List<Student>(); 11 12 private void Start() 13 { 14 //查找项羽 15 Debug.Log(FindStudent("项羽").ToString()); 16 17 //查找所有女性 18 foreach (var student in FilterFemales()) 19 { 20 Debug.Log(student.ToString()); 21 } 22 } 23 /// <summary> 24 /// 查找名为name的学生 25 /// </summary> 26 /// <param name="name">要查找的学生姓名</param> 27 Student FindStudent(string name) 28 { 29 /*//写法1 30 Student student = students.Find(delegate (Student stu) 31 { 32 return stu.name == name; 33 });*/ 34 35 //写法2 36 Student student = students.Find((Student stu) => stu.name == name); 37 38 return student; 39 } 40 /// <summary> 41 /// 筛选所有女性学生 42 /// </summary> 43 List<Student> FilterFemales() 44 { 45 /*//写法1 46 List<Student> tempStudents = students.FindAll(delegate (Student stu) 47 { 48 return stu.gender == Gender.Female; 49 });*/ 50 51 //写法2 52 List<Student> tempStudents = students.FindAll((Student stu) => stu.gender == Gender.Female); 53 54 return tempStudents; 55 } 56 } 57 /// <summary> 58 /// 学生信息 59 /// </summary> 60 [System.Serializable] 61 public class Student 62 { 63 /// <summary> 64 /// 名字 65 /// </summary> 66 public string name; 67 /// <summary> 68 /// 年龄 69 /// </summary> 70 public int age; 71 /// <summary> 72 /// 学号 73 /// </summary> 74 public int id; 75 /// <summary> 76 /// 性别 77 /// </summary> 78 public Gender gender; 79 80 public override string ToString() 81 { 82 return string.Format("{0},{1},{2},{3}", name, age, id, gender == Gender.Female ? "女" : "男"); 83 } 84 } 85 /// <summary> 86 /// 性别 87 /// </summary> 88 public enum Gender 89 { 90 /// <summary> 91 /// 女性 92 /// </summary> 93 Female, 94 /// <summary> 95 /// 男性 96 /// </summary> 97 Male, 98 }View Code
标签:return,name,C#,List,public,stu,Student,Find From: https://www.cnblogs.com/Peng18233754457/p/18039803