How to create an array with non-default repeated values in C#?


We can create an array with non-default values using Enumerable.Repeat(). It repeated a collection with repeated elements in C#. Firstly, set which element you want to repeat and how many times.

Example 1

class Program{
   static void Main(string[] args){
      var values = Enumerable.Repeat(10, 5);
      foreach (var item in values){
         System.Console.WriteLine(item);
      }
      Console.ReadLine();
   }
}

Output

10
10
10
10
10

Example 2

class Program{
   static void Main(string[] args){
      int[] values = Enumerable.Repeat(10, 5).ToArray();
      foreach (var item in values){
         System.Console.WriteLine(item);
      }
      Console.ReadLine();
   }
}

Output

10
10
10
10
10

Updated on: 19-Aug-2020

499 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements