Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Program to return a collection with repeated elements
To return a collection with repeated elements in C#, use the Enumerable.Repeat method from the System.Linq namespace. This method creates a sequence that contains one repeated value a specified number of times.
Syntax
Following is the syntax for Enumerable.Repeat method −
public static IEnumerable<TResult> Repeat<TResult>(TResult element, int count)
Parameters
-
element − The value to be repeated in the result sequence.
-
count − The number of times to repeat the value in the generated sequence.
Return Value
Returns an IEnumerable<T> that contains a repeated value.
Using Enumerable.Repeat with Numbers
Example
using System;
using System.Linq;
class Demo {
static void Main() {
// repeating element 50, two times
var num = Enumerable.Repeat(50, 2);
// displaying repeating elements
foreach (int ele in num) {
Console.WriteLine(ele);
}
}
}
The output of the above code is −
50 50
Using Enumerable.Repeat with Strings
Example
using System;
using System.Linq;
class Demo {
static void Main() {
// repeating string "Hello", three times
var greetings = Enumerable.Repeat("Hello", 3);
// displaying repeating elements
foreach (string greeting in greetings) {
Console.WriteLine(greeting);
}
}
}
The output of the above code is −
Hello Hello Hello
Using Enumerable.Repeat with Custom Objects
Example
using System;
using System.Linq;
class Student {
public string Name { get; set; }
public int Age { get; set; }
public override string ToString() {
return $"Name: {Name}, Age: {Age}";
}
}
class Demo {
static void Main() {
Student student = new Student { Name = "John", Age = 20 };
// repeating the same student object, four times
var students = Enumerable.Repeat(student, 4);
// displaying repeating elements
foreach (Student s in students) {
Console.WriteLine(s);
}
}
}
The output of the above code is −
Name: John, Age: 20 Name: John, Age: 20 Name: John, Age: 20 Name: John, Age: 20
Converting to Array or List
Example
using System;
using System.Linq;
class Demo {
static void Main() {
// create array from repeated elements
int[] repeatedArray = Enumerable.Repeat(25, 5).ToArray();
Console.WriteLine("Array: " + string.Join(", ", repeatedArray));
// create list from repeated elements
var repeatedList = Enumerable.Repeat("C#", 3).ToList();
Console.WriteLine("List count: " + repeatedList.Count);
foreach (string item in repeatedList) {
Console.WriteLine(item);
}
}
}
The output of the above code is −
Array: 25, 25, 25, 25, 25 List count: 3 C# C# C#
Conclusion
The Enumerable.Repeat method in C# provides an efficient way to create collections with repeated elements. It works with any data type and can be easily converted to arrays or lists using ToArray() and ToList() methods.
