Building a uniform sequence using the Repeat operator in LINQ C#
July 4, 2014 Leave a comment
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.