LINQ 学习路程 -- 查询操作 Deferred Execution of LINQ Query 延迟执行
延迟执行是指一个表达式的值延迟获取,知道它的值真正用到。
当你用foreach循环时,表达式才真正的执行。
延迟执行有个最重要的好处:它总是给你最新的数据
实现延迟运行
你可以使用yield关键字实现延迟加载
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);
从上面输出的结果看出:当你用foreach循环遍历时,GetTeenAgerStudents()方法才会被调用
LINQ查询的立即执行
立即执行和延迟执行相反,它迫使LINQ查询立即执行并返回结果,
IList<Student> teenAgerStudents = studentList.Where(s => s.age > 12 && s.age < 20).ToList();
IList<Student> teenAgerStudents = (from s in studentList where s.age > 12 && s.age < 20 select s).ToList();