15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Generation Methods<br />

void→IEnumerable<br />

Method Description<br />

Empty Creates an empty sequence<br />

Repeat Creates a sequence of repeating elements<br />

Range Creates a sequence of integers<br />

Empty, Repeat, and Range are static (nonextension) methods that manufacture simple<br />

local sequences.<br />

Empty<br />

Empty manufactures an empty sequence and requires just a type argument:<br />

foreach (string s in Enumerable.Empty())<br />

Console.Write (s); // <br />

In conjunction with the ?? operator, Empty does the reverse of DefaultIfEmpty. For<br />

example, suppose we have a jagged array of integers, and we want to get all the<br />

integers into a single flat list. The following SelectMany query fails if any of the inner<br />

arrays is null:<br />

int[][] numbers =<br />

{<br />

new int[] { 1, 2, 3 },<br />

new int[] { 4, 5, 6 },<br />

null // this null makes the query below fail.<br />

};<br />

IEnumerable flat = numbers.SelectMany (innerArray => innerArray);<br />

Empty in conjunction with ?? fixes the problem:<br />

IEnumerable flat = numbers<br />

.SelectMany (innerArray => innerArray ?? Enumerable.Empty ());<br />

foreach (int i in flat)<br />

Console.Write (i + " "); // 1 2 3 4 5 6<br />

Range and Repeat<br />

Range and Repeat work only with integers. Range accepts a starting index and count:<br />

foreach (int i in Enumerable.Range (5, 5))<br />

Console.Write (i + " "); // 5 6 7 8 9<br />

Repeat accepts the number to repeat, and the number of iterations:<br />

foreach (int i in Enumerable.Repeat (5, 3))<br />

Console.Write (i + " "); // 5 5 5<br />

412 | Chapter 9: LINQ Operators

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

Saved successfully!

Ooh no, something went wrong!