8委托、lamdba、泛型、Linq结合运用

解决多条件问题

1、创建一个学生类

class Student
    {
        public int Id { get; set; }//学生编号

        public string Name { get; set; }//姓名

        public int Age { get; set; }//年龄

        public int ClassId { get; set; }//班级编号

    }

2、创建一个学生类类型的集合,并且初始化几条数据

List<Student> Students = new List<Student>()
            {
                new Student(){ Id=0,Name="张三",Age=18,ClassId=001 },
                new Student(){ Id=1,Name="李四",Age=20,ClassId=002 },
                new Student(){ Id=2,Name="王五",Age=16,ClassId=002 },
            };

3、现在有如下逻辑需要

1)根据学生年龄为条件,查询年龄大于或等于20岁的所有学生信息
2)根据学生班级为条件,查询年班级编号为001的所有学生信息

那么,按照逻辑可以写两个方法解决:如:
image

4、那么,如果有更多的条件,那这样就要写很多的方法,;因此可以使用委托解决条件不同需要写不同方法的问题

所以,我们使用委托,将一个方法传进来,在判断的时候执行即可。

//根据条件进行查询的方法
        public static List<Student> GetStudents3(List<Student> Students, Func<Student, bool> func)
        {

            List<Student> tempStudents = new List<Student>();
            foreach (var item in Students)
            {
                if (func(item))
                {
                    tempStudents.Add(item);
                }
            }

            return tempStudents;
        }

这样,我们在执行的时候就可以根据不同的条件传不同的方法了

5、调用

比如:根据年龄条件来查询,就写一个年龄条件的方法,调用查询方法的时候将方法当作参数传进去即可。
定义一个根据年龄查询的方法:

public static bool ByAge(Student student)
        {
            return student.Age >= 20;
        }

调用的时候直接将上面的方法传进去,或者用lamdba写一个符合委托的匿名方法也可以,如:

 List<Student> StudentsNew = GetStudents3(Students, ByAge);

List<Student> StudentsNew2 = GetStudents3(Students, (a) => { return a.Age >= 20; });

推荐使用匿名方法



自定义一个Linq的where方法

linq的where方法和上面定义的委托为参数的方法原理基本一致,只需要将它改为一个扩展方法,并把里面的对象类型改为泛型即可

//根据条件进行查询的方法
        public static List<TSource> MyWhere<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> func)
        {

            List<TSource> tempStudents = new List<TSource>();
            foreach (var item in source)
            {
                if (func(item))
                {
                    tempStudents.Add(item);
                }
            }

            return tempStudents;
        }

用linq方法调用

1,扩展方式调用

 List<Student> StudentsNew = Students.MyWhere((a) => { return a.Age >= 20; }).ToList();

 List<Student> StudentsNew2 = Students.Where((a) => { return a.Age >= 20; }).ToList();
posted @ 2021-11-02 16:12  青仙  阅读(66)  评论(0编辑  收藏  举报