LINQ Generation Operators


Generation operators are used to create sequences of data in a collection. They are especially useful for producing sequences or initializing data in various scenarios. In LINQ and other query languages, generation operators can create collections based on specific rules or patterns.

Here’s a look at some common generation operators.

  1. Range
  2. Repeat
  3. Empty

1. Range

Generates a sequence of integral values within a specified range. Use Range to create a sequence of integers from a starting value up to a specified count.

Example

var range = Enumerable.Range(1, 5); // Generates: { 1, 2, 3, 4, 5 }

2. Repeat

Generates a sequence that contains a single value repeated a specified number of times. Use Repeat when you need a collection with a repeated element.

Example

var repeated = Enumerable.Repeat("Hello", 3); // Generates: { "Hello", "Hello", "Hello" }

3. Empty

Creates an empty sequence of a specified type. Use Empty when you need to represent a sequence with no elements.

Example

var empty = Enumerable.Empty<int>(); // Generates: { }

Prev Next