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, Wash. He has worked on several Microsoft products including Azure and Bing. James can be reached at [email protected].

comments powered by Disqus

Featured

.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.

Upcoming Events