Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way to create a List<T> of a repeated element

With the String class, you can do:

string text = new string('x', 5); //text is "xxxxx" 

What's the shortest way to create a List< T > that is full of n elements which are all the same reference?

like image 827
xyz Avatar asked Jul 13 '09 16:07

xyz


People also ask

How do you create a repeated value list?

Using the * Operator The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list. Here, we just have to keep in mind that to repeat the elements n times, we will have to multiply the list by (n+1).


1 Answers

Try the following

var l = Enumerable.Repeat('x',5).ToList(); 
like image 147
JaredPar Avatar answered Sep 20 '22 07:09

JaredPar