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 }
View Code
复制代码

posted @   朋丶Peng  阅读(597)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示