C# LINQ Enumerable.Repeat Method in ASP.Net

Updated on 10 Apr 2012,
Published on 25 Oct 2010

The Repeat method of System.Linq.Enumerable class enables to generate a sequence containing the multiple copies of specified value. It generates the specified number of repetitions of a specified value in the form of IEnumerable<T> sequence. The LINQ Repeat method does not have any overloaded function and has a following simple form:

public static IEnumerable<TResult> Repeat<TResult>(TResult element, int count);

It accepts two parameters where the first parameter specifies the value to be repeated and the second parameter specifies the number of times to repeat the value.

C# LINQ Repeat Method Example in ASP.Net

IEnumerable<Product> query = Enumerable.Repeat(new Product { ProductID = 1, ProductName = "Cheese" }, 2);

foreach (Product product in query)
{
    Response.Output.Write("{0} - {1}<br />", product.ProductID, product.ProductName);
}

// Output:
// 1 - Cheese
// 1 - Cheese

The C# Product class code:

public class Product 
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
}

The above C# sample code illustrates the use of LINQ Repeat method. In the example, we have specified a single object of Product class, as a first parameter of Repeat method, initialized with values for its ProductID and ProductName properties. For the count parameter we have specified a value 2 that will generate a sequence containing the two repetitions of the specified object as shown in above sample output.

Continue to next tutorial: C# LINQ Enumerable.Reverse Method in ASP.Net to learn how to invert the order of the element in a sequence.

0 Responses to "C# LINQ Enumerable.Repeat Method in ASP.Net"
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers