Enumerable.Repeat<TResult> Method
Signature
public static IEnumerable<TResult> Repeat<TResult>(TResult element, int count)
Parameters
element
(TResult)- The element to repeat.
count
(Int32)- The number of times to repeat the element.
Returns
An IEnumerable<TResult>
that contains a repeated sequence of the specified element.
Remarks
This method returns an enumerable collection that yields the specified element
exactly count
times.
If count
is less than or equal to zero, an empty enumerable is returned.
Examples
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
// Create an enumerable that repeats the number 5 three times.
IEnumerable<int> repeatedNumbers = Enumerable.Repeat(5, 3);
// Output the elements.
foreach (int num in repeatedNumbers)
{
Console.WriteLine(num);
}
// Output:
// 5
// 5
// 5
// Create an enumerable that repeats the string "hello" twice.
IEnumerable<string> repeatedStrings = Enumerable.Repeat("hello", 2);
foreach (string str in repeatedStrings)
{
Console.WriteLine(str);
}
// Output:
// hello
// hello
}
}