3人对饮

导航

 

LINQ扩展方法执行时,应用程序不会真正构建集合,只有在遍历集合的时候(使用 foreach)才会对集合进行枚举。

static void DoWork()
        {
            Tree<Employee> empTree = new Tree<Employee>(new Employee 
              { Id = 1, FirstName = "Janet", LastName = "Gates", Department = "IT"});
            empTree.Insert(new Employee 
              { Id = 2, FirstName = "Orlando", LastName = "Gee", Department = "Marketing"});
            empTree.Insert(new Employee 
              { Id = 4, FirstName = "Keith", LastName = "Harris", Department = "IT" });
            empTree.Insert(new Employee 
              { Id = 6, FirstName = "Lucy", LastName = "Harrington", Department = "Sales" });
            empTree.Insert(new Employee 
              { Id = 3, FirstName = "Eric", LastName = "Lang", Department = "Sales" });
            empTree.Insert(new Employee 
              { Id = 5, FirstName = "David", LastName = "Liu", Department = "Marketing" });

            Console.WriteLine("All employees");
            var allEmployees = from e in empTree.ToList<Employee>()
                               select e;
           
            empTree.Insert(new Employee
                               {
                                   Id = 7,
                                   FirstName = "Donald",
                                   LastName = "Blanton",
                                   Department = "IT"
                               });
            Console.WriteLine("\nEmployee added");
            

            Console.WriteLine("All employees");
            foreach (var emp in allEmployees)
            {
                Console.WriteLine(emp);
            }

使用ToList()方法获取数据缓存副本。ToArray()方法将数据缓存到数组。因为使用ToList()方法,所以上述代码的输出不会列出 Id=7 的记录。去掉ToList<Employee>(),
MSDN讲的很好http://msdn.microsoft.com/zh-cn/library/bb397906.aspx

 

posted on 2012-09-18 19:09  3人对饮  阅读(159)  评论(0编辑  收藏  举报