LINQ Repeat Method

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

Syntax of LINQ Repeat Method

Following is the syntax of the LINQ Repeat method to generate repeated numbers 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 the above syntax, we defined the Repeat method with two parameters. Here, the first parameter tells the starting elements of the integer, and the second parameter is the one that tells how many times the same number is repeated in sequence.

Example of LINQ Repeat Method

Following is the example of the LINQ Repeat method to generate a collection that contains the 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 the above example, we defined the Repeated method with a range from (100, 10), so it will take starting number as ”100” and it will generate the same number as “10” times because here we defined the second parameter as 10 so it will return the same number 10 times.

Output LINQ Repeat Method Example

Following is the result of the LINQ Repeat method example.

 

100
100
100
100
100
100
100
100
100
100

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