了解C#中的懒惰评估

时间:2016-11-09 23:04:28

标签: c# linq lazy-evaluation

我有这样的代码

 class Context
    {
        public List<Student> lists;
        public Context()
        {
            lists = new List<Student>() {
                new Student { Name="foo",Standard="first",subjects=new Subjects { Geography=50,History=81,Science=70} },
                new Student { Name="carl",Standard="first",subjects=new Subjects { Geography=40,History=51,Science=50} },
                new Student { Name="ben",Standard="first",subjects=new Subjects { Geography=30,History=91,Science=60} },
                new Student { Name="peter",Standard="first",subjects=new Subjects { Geography=80,History=71,Science=40} }              
            };
        }
    }
    class Client
    {
        static void Main(string[] args)
        {
            List<Student> lists = new Context().lists;
            var result = lists.Where(x => x.subjects.History > 60);
            lists.Add(new Student { Name = "tan", Standard = "first", subjects = new Subjects { Geography = 40, History = 81, Science = 60 } });
            lists.Add(new Student { Name = "ran", Standard = "first", subjects = new Subjects { Geography = 30, History = 70, Science = 50 } });
            lists.Add(new Student { Name = "ranky", Standard = "first", subjects = new Subjects { Geography = 20, History = 31, Science = 40 } });
            lists.Add(new Student { Name = "franky", Standard = "first", subjects = new Subjects { Geography = 50, History = 51, Science = 30 } });
            foreach (var data in result) {
            Console.WriteLine(data);
        }
        }
    }

现在在调试时,在添加一些元素之前,当我将鼠标放在变量上时,我得到的结果是这样的

enter image description here

将一些元素添加到列表后,当我将鼠标悬停在变量上时,我得到的结果就像这样

enter image description here 但是根据Lazy Execution概念,它在到达foreach方法时加载数据,那么为什么数据已经加载并在调试器中被看到。我错过了理解懒惰评估的内容 更新1 根据之前关于我的截图,如果点击“结果视图”强制加载数据,那么这是我的第二个scenerio,我只是加载数据,这可以从截图中看到

enter image description here 但是当调试器移动到下一个元素时,计数会增加。

enter image description here 是不是假设在使用foreach进行调用时加载数据?请帮助我了解惰性评估的工作原理。谢谢。

1 个答案:

答案 0 :(得分:2)

这是因为您没有将连接结果分配给任何内容:

numbers.Concat(num2);

应该是:

numbers = numbers.Concat(num2).ToArray();