Linq 延迟加载

时间:2021-10-27 10:48:34
 IList<Student> ssList = new List<Student>() {
new Student() { StudentID = , StudentName = "John", } ,
new Student() { StudentID = , StudentName = "Steve" } ,
new Student() { StudentID = , StudentName = "Bill" } ,
new Student() { StudentID = , StudentName = "Ram" } ,
new Student() { StudentID = , StudentName = "Ron" }
}; IEnumerable<Student> r = ssList.Where(w => w.StudentID > );
r.ToList().ForEach(f => Console.WriteLine(f.StudentID));//3,4,5
Console.WriteLine("--------------"); ssList.Add(new Student { StudentID = , StudentName = "wjire" });
r.ToList().ForEach(f => Console.WriteLine(f.StudentID));//3,4,5,6
Console.WriteLine("--------------");

集合 r 是 IEnumerable<T> 类型,该类型的对象具有延迟加载的特性,也就是说,

IEnumerable<Student> r = ssList.Where(w => w.StudentID > 2);

这句代码执行后, r 中并没有值,只有当 r 使用时,也就是上述代码中的 ToList() ,才会去遍历 ssList 集合,注意,是去遍历 "ssList" 集合取数据.

所以下面那句显示代码执行时,ssList 集合中已经有6了,所以能显示出来.