The solution is useful because it saves you space. Most programming optimizations compromise between space (disk, memory, network) and processing. Exit as a programming construct allows you to repeatedly iterate over a collection without requiring a separate copy of the collection for each iteration.
consider this example:
static IEnumerable<Person> GetAllPeople() { return new List<Person>() { new Person() { Name = "George", Surname = "Bush", City = "Washington" }, new Person() { Name = "Abraham", Surname = "Lincoln", City = "Washington" }, new Person() { Name = "Joe", Surname = "Average", City = "New York" } }; } static IEnumerable<Person> GetPeopleFrom(this IEnumerable<Person> people, string where) { foreach (var person in people) { if (person.City == where) yield return person; } yield break; } static IEnumerable<Person> GetPeopleWithInitial(this IEnumerable<Person> people, string initial) { foreach (var person in people) { if (person.Name.StartsWith(initial)) yield return person; } yield break; } static void Main(string[] args) { var people = GetAllPeople(); foreach (var p in people.GetPeopleFrom("Washington")) {
(Obviously, you don’t need to use revenue with extension methods, it just creates a powerful paradigm to think about data.)
As you can see, if you have many of these “filtering” methods (but it can be any method that does some work on a list of people), you can link many of them together without requiring additional storage space for each step. This is one way to enhance your programming language (C #) to better express your decisions.
The first side effect of the output is that it delays the execution of the filtering logic until you require it. If you therefore create a variable of type IEnumerable <> (with outputs), but never repeat it, you never execute logic or consume space, which is a powerful and free optimization.
Another side effect is that the output works on the lowest common collection interface (IEnumerable <>), which allows library-like code to be created with wide applicability.
Pieter Breed Nov 25 '08 at 15:19 2008-11-25 15:19
source share