Linq语句只有在调用结果的时候才会真正执行,如下
1 static void Main(string[] args) 2 { 3 PersonList personList = new PersonList(); 4 personList.CurrentIndex = 0; 5 var r1 = from p in personList where p.Age == 18 select p ; 6 Console.WriteLine(personList.CurrentIndex.ToString()); 7 personList.CurrentIndex = 0; 8 var r2 = (from p in personList where p.Age >= 20 select p).First(); 9 Console.WriteLine(personList.CurrentIndex.ToString()); 10 personList.CurrentIndex = 0; 11 var r3 = (from p in personList select p).Take(2); 12 Console.WriteLine(personList. CurrentIndex.ToString()); 13 14 Console.ReadLine(); 15 } 16 } 17 class Person 18 { 19 public string Name { get; set; } 20 public int Age { get; set; } 21 public Person(string name, int age) 22 { 23 Name = name; 24 Age = age; 25 } 26 } 27 class PersonList : IEnumerable<Person> 28 { 29 List<Person> pList = new List<Person>() 30 { 31 new Person("Mike",20), 32 new Person("John",23), 33 new Person("Jack",18), 34 new Person("Tom",34) 35 }; 36 public void Add(Person person) 37 { 38 pList.Add(person); 39 } 40 public int CurrentIndex { get; set; } 41 public IEnumerator<Person> GetEnumerator() 42 { 43 foreach (var p in pList) 44 { 45 CurrentIndex++; 46 yield return p; 47 } 48 } 49 IEnumerator IEnumerable.GetEnumerator() 50 { 51 return GetEnumerator(); 52 } 53 }
结果:
0,
1,
0.
第5行和第11行只有在调用r1,r3的时候才会真正执行,而我们并没有调用r1和r3,所以CurrentIndex为0,而第8行则直接执行。
如果linq语句立刻执行,可以在后边加上ToList<>等方法。