03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

338 ❘ CHAPTER 14 Collection Classes<br />

added to the collection. The following code uses that technique to initialize a Stack and Queue of<br />

Author objects.<br />

Stack authorStack = new Stack(<br />

new Author[]<br />

{<br />

new Author("Terry", "Pratchett"),<br />

new Author("Jasper", "Fforde"),<br />

new Author("Tom", "Holt"),<br />

}<br />

);<br />

Queue authorQueue = new Queue(<br />

new Author[]<br />

{<br />

new Author("Terry", "Pratchett"),<br />

new Author("Jasper", "Fforde"),<br />

new Author("Tom", "Holt"),<br />

}<br />

);<br />

Iterators<br />

One advantage of collection classes is that you can use a foreach loop to enumerate over their items.<br />

<strong>C#</strong> also allows you to write iterators. An iterator is a method that yields a sequence of results. The<br />

program can use a foreach loop to enumerate the values the iterator yields. In that sense iterators<br />

resemble collections; although they don’t need to store items in some sort of data structure.<br />

The easiest way to make an iterator is to create a method that returns IEnumerable or a generic<br />

type such as IEnumerable. The method should generate its values and use a yield<br />

return statement to return them to the code that is looping over the enumeration.<br />

For example, the following iterator yields a list of prime numbers between startNumber<br />

and stopNumber.<br />

// Enumerate prime numbers between startNumber and stopNumber.<br />

public IEnumerable Primes(int startNumber, int stopNumber)<br />

{<br />

// Define a lambda expression that tests primality.<br />

Func isPrime = x =><br />

{<br />

if (x == 1) return false; // 1 is not prime.<br />

if (x == 2) return true; // 2 is prime.<br />

if (x % 2 == 0) return false; // Even numbers are not prime.<br />

for (int i = 3; i * i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!