LINQ Repeat Method

In LINQ, Repeat method or operator is used to generate collection with same number as repeated times based on specified index values.

Syntax of LINQ Repeat Method

Following is the syntax of LINQ Repeat method to generate repeated number based on specified index values.

 

C# Code

 

IEnumerable<int> obj = Enumerable.Repeat(100, 10); 

VB.NET Code

 

Dim obj As IEnumerable(Of Integer) = Enumerable.Repeat(100, 10)

If you observe above syntax we defined Repeat method with two parameters. Here first parameter tells the starting elements of integer and the second parameter is the one that tells how many times same number repeated in sequence.

Example of LINQ Repeat Method

Following is the example of LINQ Repeat method to generate a collection that contains same number as repeated times.

 

C# Code

 

using System;

using System.Collections.Generic;

using System.Linq;

 

namespace Linqtutorials

{

class Program

{

static void Main(string[] args)

{

IEnumerable<int> obj = Enumerable.Repeat(100, 10);

foreach (var item in obj)

{

Console.WriteLine(item);

}

Console.ReadLine();

}

}

}

VB.NET Code

 

Module Module1

Sub Main()

Dim obj As IEnumerable(Of Integer) = Enumerable.Repeat(100, 10)

For Each item In obj

Console.WriteLine(item)

Next

Console.ReadLine()

End Sub

End Module

If you observe above example we defined Repeated method with range from (100, 10) so it will take starting number as ”100” and it will generate same number as “10” times because here we defined second parameter as 10 so it will return same number 10 times.

Output LINQ Repeat Method Example

Following is the result of LINQ Repeat method example.

 

100

100

100

100

100

100

100

100

100

100

This is how we can use LINQ Repeat method to generate collection with repeated number based on specified length in c#, vb.net.