In this blog we illustrate the generation operators in linq.
We have a three Generation Operators :
1. Empty
2. Range
3. Repeat
1. Empty:-
Empty operator is used to return an empty sequence of the type that is specified . It is a static method involved in Enumerable static class.
Example:-
To understand Empty operator, see the below code:-
var data1 = Enumerable.Empty<int>();
var data2 = Enumerable.Empty<Employee>();
Console.WriteLine("Count: {0} ", data1.Count());
Console.WriteLine("Type: {0} ", data1.GetType().Name);
Console.WriteLine("Count: {0} ", data2.Count());
Console.WriteLine("Type: {0} ", data2.GetType().Name);
Output:-

2. Range:-
Range operator returns an integer sequence with specified number of items and sequential values starting from the first item. It takes two parameters, start index and end index.
Example:-
In the below code, we generate an integer sequence from 1 to 20.
Code:-
var dataCollection = Enumerable.Range(1, 20);
Console.WriteLine("Total Count: {0} ", dataCollection.Count());
for (int i = 0; i < dataCollection.Count(); i++)
Console.WriteLine("Value at index {0} : {1}", i, dataCollection.ElementAt(i));
Output:-

3. Repeat:-
Repeat operator is used to repeat a specified statement/item. It accepts two parameters, First parameter is the statement/item that is to be repeated and the second parameter is used to define a number of times the first parameter is to be repeated.
Example:-
Code:-
var dataCollection = Enumerable.Repeat<string>("Dot Net", 3);
Console.WriteLine("Total Count: {0} ", dataCollection.Count());
for (int i = 0; i < dataCollection.Count(); i++)
Console.WriteLine("Value at index {0} : {1}", i, dataCollection.ElementAt(i));
Output:-

0 Comment(s)