6. 延迟执行查询

概念

表达式被延迟执行,直到需要调用它的值时才真正执行;

延迟执行适用于集合,也适用于Linq to SQL,Linq to Entities,Linq-to-XML,etc

例子一

  • 延迟执行在真实需要的时候才执行,某种程度上提升了性能;

6. 延迟执行查询

例子二:

  • 延迟执行,是在最新的值上面执行的,每次都执行;

6. 延迟执行查询

如何自己实现延迟方法

public static class EnumerableExtensionMethods
{
    public static IEnumerable<Student> GetTeenAgerStudents(this IEnumerable<Student> source)
    {

        foreach (Student std in source)
        {
            Console.WriteLine("Accessing student {0}", std.StudentName);

            if (std.age > 12 && std.age < 20)
                yield return std;
        }
    }
}


IList<Student> studentList = new List<Student>() {
            new Student() { StudentID = 1, StudentName = "John", age = 13 } ,
            new Student() { StudentID = 2, StudentName = "Steve",  age = 15 } ,
            new Student() { StudentID = 3, StudentName = "Bill",  age = 18 } ,
            new Student() { StudentID = 4, StudentName = "Ram" , age = 12 } ,
            new Student() { StudentID = 5, StudentName = "Ron" , age = 21 }
        };

var teenAgerStudents = from s in studentList.GetTeenAgerStudents()
                        select s;

foreach (Student teenStudent in teenAgerStudents)
    Console.WriteLine("Student Name: {0}", teenStudent.StudentName);

直接执行

IList<Student> teenAgerStudents =
                studentList.Where(s => s.age > 12 && s.age < 20).ToList();
上一篇:C#:SqlSugar中时间戳(TimeStamp)的使用


下一篇:springboot管理及监控之Micrometer