C# 用代码解析Linq查询原理

Student实体类
public class Student
{
    public int Age { get; set; }
    public string Name { get; set; }
    public string QQ { get; set; }
}
//初始化两个集合的数据
List<int> intList = new List<int> { 1, 324, 5, 56, 123, 545, 23, 6 };
List<Student> studentList = new List<Student>()
{
    new Student()
    {
        Age=18,
        Name="lqwvje",
        QQ="78630559"
    },
    new Student()
    {
        Age=19,
        Name="995w",
        QQ="2334160"
    },
    new Student()
    {
        Age=20,
        Name="luofenming",
        QQ="813200300"
    }
};
//查询原理  通过这个 我们也可以联想到其它的通用方法进行数据处理
public List<T> LqwvjeWhere1<T>(List<T> listData, Func<T, bool> func)
{
    List<T> resultList = new List<T>();
    foreach (T t in listData)
    {
        if (func.Invoke(t))
        {
            resultList.Add(t);
        }
    }
    return resultList;
}

//方法调用
{
List<int> d = LqwvjeWhere1(intList, i => i > 5);//查询大于5的数据
List<Student> students = LqwvjeWhere1<Student>(studentList, student => student.Age > 18);//查询年龄大于18的数据
}

以下是按.net 框架封装的原理
public static class LqwvjeExtend//静态类
{
    public static List<T> LqwvjeWhere<T>(this List<T> listData, Func<T, bool> func)//注意要静态  参数集合前面要加个this
    {
        List<T> resultList = new List<T>();
        foreach (T t in listData)
        {
            if (func.Invoke(t))
            {
                resultList.Add(t);
            }
        }
        return resultList;
    }
}
//方法调用
List<Student> list = studentList.LqwvjeWhere<Student>(student => student.Age > 18);

评论