Demystifying the C# Yield-Return Mechanism: Listing 3.

Person class with yield-return filters.

class Person
{
  private string name;
  private int age;

  public Person(string name, int age)
  {
    this.name = name;
    this.age = age;
  }

  public string Name { get { return this.name; } }

  public int Age { get { return this.age; } }

  public override string ToString() { return name + " " + age; }

  public static IEnumerable<Person> GetYoung(IEnumerable<Person> source)
  {
    foreach (Person p in source) {
      if (p.age < 20)
        yield return p;
    }
  }
  public static IEnumerable<Person>
    GetStartWithA(IEnumerable<Person> source)
  {
    foreach (Person p in source) {
      if (p.name.StartsWith("A"))
        yield return p;
    }
  }
} // Person

About the Author

Dr. James McCaffrey works for Microsoft Research in Redmond, WA. James has worked on several key Microsoft products such as Internet Explorer and Bing. James can be reached at jamccaff@microsoft.com.