Generation Methods

Method

Description

Empty

Creates an empty sequence

Repeat

Creates a sequence of repeating elements

Range

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 6

Range 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

Get LINQ Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.