Building a uniform sequence using the Repeat operator in LINQ C#

Using the Repeat operator you can create sequences where the same input object is repeated a number of times.

Its usage is very simple. Say you need a list of integers with number 1 repeated 10 times:

IEnumerable<int> integers = Enumerable.Repeat<int>(1, 10);
foreach (int i in integers)
{
	Console.WriteLine(i);
}

…which simply prints “1” 10 times.

Be careful with reference types. If you want identical objects in the sequence that can be modified separately then use the new keyword directly in the Repeat method:

IEnumerable<Band> bands = Enumerable.Repeat<Band>(new Band() { Name = "Band" }, 10);

Otherwise all objects will have the same reference:

Band band = new Band() { Name = "Band" };
IEnumerable<Band> bands2 = Enumerable.Repeat<Band>(band, 10);

…and modifying one will modify all references.

View the list of posts on LINQ here.

Unknown's avatarAbout Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.