Generation Methods
Method | Description |
|---|---|
| Creates an empty sequence |
| Creates a sequence of repeating elements |
| Creates a sequence of integers |
Empty, Repeat, and Range are static (nonextension) methods that
manufacture simple local sequences.
Empty
Empty manufactures an empty
sequence and requires just a type argument:
foreach (string s in Enumerable.Empty<string>()) Console.Write(s); // <nothing>
In conjunction with the ?? operator, Empty does the reverse of DefaultIfEmpty. For example, suppose we have
a jagged array of integers, and we want to get all the integers into a
single flat list. The following SelectMany query fails if any of the inner
arrays is null:
int[][] numbers =
{
new int[] { 1, 2, 3 },
new int[] { 4, 5, 6 },
null // this null makes the query below fail.
};
IEnumerable<int> flat =
numbers.SelectMany (innerArray =>innerArray);Empty in conjunction with ??
fixes the problem:
IEnumerable<int> flat = numbers
.SelectMany (innerArray =>
innerArray ?? Enumerable.Empty <int>() );
foreach (int i in flat)
Console.Write (i + " "); // 1 2 3 4 5 6Range and Repeat
Range and Repeat work only with integers. Range accepts a starting index and
count:
foreach (int i in Enumerable.Range (5,5)) Console.Write (i + " "); // 5 6 7 8 9
Repeat accepts the number to
repeat and the number of iterations:
foreach (int i in Enumerable.Repeat (5,3)) Console.Write (i + " "); // 5 5 5
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access