Author : Rahul
Last Modified : 13-Jul-2021
Complexity : Beginner
Generation Operator in LINQ
Generation Operator in LINQ is used to return the range of result or repetition of the result. There are two Generation Operator are available in LINQ as follow:
- RANGE
- REPEAT
RANGE OPERATOR
RANGE operator is used to return the collection with a specified number of elements and each element contains sequential value. Range keyword is used for this purpose. Below is the example in this category.
Query to generate numbers from 10 to 19 using Range.
class Program
{
static void Main(string[] args)
{
//Linq Query
var result_Linq = Enumerable.Range(10, 10);
//Lambda Expression
var result_Lambda = Enumerable.Range(10, 10);
//Display Linq Query Result
Console.WriteLine("Numbers from 10 to 19 (Using Linq):");
foreach (var item in result_Linq)
{
Console.WriteLine(item);
}
//Display Lambda Expression Result
Console.WriteLine("Numbers from 10 to 19 (Using Lambda):");
foreach (var item in result_Lambda)
{
Console.WriteLine(item);
}
Console.Read();
}
}
Output
Numbers from 10 to 19 (Using Linq):
10
11
12
13
14
15
16
17
18
19
Numbers from 10 to 19 (Using Lambda):
10
11
12
13
14
15
16
17
18
19
REPEAT OPERATOR
REPEAT operator is used to return the collection with a specified number of elements and each element contains the same value. Repeat keyword is used for this purpose. Below is the example in this category.
Query to generate number 7, 5 times using Repeat.
class Program
{
static void Main(string[] args)
{
//Linq Query
var result_Linq = Enumerable.Repeat(7, 5);
//Lambda Expression
var result_Lambda = Enumerable.Repeat(7, 5);
//Display Linq Query Result
Console.WriteLine("Numbers 7, 5 times (Using Linq):");
foreach (var item in result_Linq)
{
Console.WriteLine(item);
}
//Display Lambda Expression Result
Console.WriteLine("Numbers 7, 5 times (Using Lambda):");
foreach (var item in result_Lambda)
{
Console.WriteLine(item);
}
Console.Read();
}
}
Output
Numbers 7, 5 times (Using Linq):
7
7
7
7
7
Numbers 7, 5 times (Using Lambda):
7
7
7
7
7