Linq Repeat Method in C#

Linq Repeat Method in C# with Examples

In this article, I am going to discuss the LINQ Repeat Method in C# with an example. The Repeat method belongs to the Generation Operator category. Please read our previous article before proceeding to this article where we discussed the LINQ Range Method with some examples.

Linq Repeat Method in C#:

The LINQ Repeat Method is used to generate a sequence or collection that with a specified number of elements and each element contains the same value. The following is the signature of this method.

Linq Repeat Method in C# with Examples

The Repeat method has 2 integer parameters. The first parameter (i.e. TResult element) specifies the value to be repeated. The second parameter (i.e. int count) specifies the number of times to repeat the value. The return type of this method is IEnumerable<int> which is going to contain the repeated values. Here TResult specifies the data type of the value that is going to be repeated in the result sequence.

Note: When the count value is less than 0 then it will through ArgumentOutOfRangeException.

Example:

The following example shows how to use the Repeat method to generate a sequence of a repeated value.

using System.Linq;
using System;
using System.Collections.Generic;

namespace LinqDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable<string> repeatStrings = Enumerable.Repeat("Welcome to DOT NET Tutorials", 10);

            foreach (String str in repeatStrings)
            {
                Console.WriteLine(str);
            }
            Console.ReadKey();
        }
    }
}

Output:

Linq Repeat Method in C# with Example

Note: The LINQ Repeat method is implemented using the deferred execution. So, the immediate return value is an object which stores all the required information to perform an action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using a for each loop.

In the next article, I am going to discuss the Linq Empty Method with some examples. Here, in this article, I try to explain the Linq Repeat Method in C# with an example.

Leave a Reply

Your email address will not be published. Required fields are marked *