Summary: in this tutorial, you will learn how to use the LINQ Repeat()
method to generate a sequence that contains one repeated value.
Introduction to the LINQ Repeat() method
The Repeat()
method generates a sequence that contains one repeated value:
IEnumerable<TResult> Repeat<TResult> (TResult element, int count);
Code language: C# (cs)
In this syntax:
TResult
represents the type of value to be repeated in the result sequence.element
has the typeTResult
, which represents the value to be repeated.count
is an integer that denotes the number of times to repeat theelement
in the generated sequence.
The Repeat()
method returns an IEnumerable<T>
that contains the repeated elements count times.
LINQ Repeat() method example
Let’s take some examples of using the Repeat()
method.
1) Using the Repeat() method to generate a sequence of numbers
The following example uses the Repeat()
method to generate a sequence of four numbers 9:
using static System.Console;
var numbers = Enumerable.Repeat(9, 4);
foreach (var number in numbers)
{
WriteLine(number);
}
Code language: C# (cs)
Output:
9
9
9
9
Code language: C# (cs)
2) Using the Repeat() method to generate a sequence of strings
The following example uses the Repeat()
method to generate a sequence of strings:
using static System.Console;
var messages = Enumerable.Repeat("bye", 3);
foreach (var message in messages)
{
WriteLine(message);
}
Code language: C# (cs)
Output:
bye
bye
bye
Code language: plaintext (plaintext)
Summary
- Use LINQ
Repeat()
method to generate a sequence that contains an element repeated N times.
Was this tutorial helpful ?