Linq 延迟加载

 IList<Student> ssList = new List<Student>() {
                    new Student() { StudentID = 1, StudentName = "John", } ,
                    new Student() { StudentID = 2, StudentName = "Steve" } ,
                    new Student() { StudentID = 3, StudentName = "Bill" } ,
                    new Student() { StudentID = 4, StudentName = "Ram" } ,
                    new Student() { StudentID = 5, StudentName = "Ron" }
                };

            IEnumerable<Student> r = ssList.Where(w => w.StudentID > 2);
            r.ToList().ForEach(f => Console.WriteLine(f.StudentID));//3,4,5
            Console.WriteLine("--------------");

            ssList.Add(new Student { StudentID = 6, 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了,所以能显示出来.

 

posted @ 2017-12-31 17:52  热敷哥  阅读(167)  评论(0编辑  收藏  举报