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)

…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.

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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

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

%d bloggers like this: