1. 程式人生 > >yield return 返回迭代器

yield return 返回迭代器

 public class Person
    {
        public string firstName;
        public string lastName;
        public int age;

        public Person(string fName, string lName, int age)
        {
            this.firstName = fName;
            this.lastName = lName;
            this.age = age;
        }
    }

   


    
public class People : IEnumerable { private Person[] _people; public People(Person[] pArray) { _people = new Person[pArray.Length]; for (int i = 0; i < pArray.Length; i++) { _people[i] = pArray[i]; } }
public IEnumerator GetEnumerator() { for (int i = 0; i < _people.Length; i++) //int i = _people.Length - 1; i >= 0; --i { yield return _people[i]; } } } public class PeopleEnum : IEnumerator { public Person[] _people;
// Enumerators are positioned before the first element // until the first MoveNext() call. int position = -1; public PeopleEnum(Person[] list) { _people = list; } public bool MoveNext() { position++; return (position < _people.Length); } public void Reset() { position = -1; } public object Current { get { try { return _people[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } } class Program { static void Main(string[] args) { Person[] peopleArray = new Person[3] { new Person("John", "Smith",9), new Person("Jim", "Johnson",6), new Person("Sue", "Rabon",90) }; People peopleList = new People(peopleArray); //People yongPeople; //foreach //不使用yield return的查詢小10歲的演算法 List<Person> allPerson = new List<Person>(); allPerson.AddRange( new Person[3] { new Person("John", "Smith",9), new Person("Jim", "Johnson",6), new Person("Sue", "Rabon",90) } ); List<Person> less10Person = new List<Person>(); foreach(Person p in allPerson) { if (p.age < 10) { less10Person.Add(p); } } foreach (Person p in less10Person) { Console.WriteLine(p.firstName + "." + p.lastName); } Console.WriteLine("-----------------------"); //使用yield return查詢年齡小於多少的集合。 IEnumerable children = GetPeopleByAge(peopleList, 10); foreach (Person p in GetPeopleByAge(peopleList, 10)) { Console.WriteLine(p.firstName + "." + p.lastName); } } private static IEnumerable GetPeopleByAge(People peopleList, int age) { foreach (Person p in peopleList) { if (p.age < age) { yield return p; } } }