How does the following LINQ statement work?

后端 未结 5 1151
南旧
南旧 2021-01-29 22:24

How does the following LINQ statement work?

Here is my code:

var list = new List{1,2,4,5,6};
var even = list.Where(m => m%2 == 0);
list.Add         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-29 22:52

    You are getting this result because of deferred execution which means result is actually not evaluated until its first accessed.

    To make it more clear just add 10 to the list at end of your snipet and then print again you will not get 10 in output

         var list = new List{1,2,4,5,6};
        var even = list.Where(m => m%2 == 0).Tolist();
        list.Add(8);
        foreach (var i in even)
        {
            Console.WriteLine(i);
        }
    //new*
        list.Add(10);
        foreach (var i in even)
        {
            Console.WriteLine(i);
        }
    

提交回复
热议问题