views:

190

answers:

4

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?

+25  A: 

Try the following

var l = Enumerable.Repeat('x',5).ToList();
JaredPar
+2  A: 

Fastest way I know is:

int i = 0;
MyObject obj = new MyObeject();
List<MyObject> list = new List<MyObject>();
for(i=0; i< 5; i++)
{
    list.Add(obj);
}

which you can make an extention method if you want to use it multiple times.

public void AddMultiple(this List<T> list, T obj, int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        list.Add(obj);
    }
}

Then you can just do:

List<MyObject> list = new List<MyObject>();
MyObject obj = new MyObject();
list.AddMultiple(obj, 5);
Andy_Vulhop
Thanks - I might do an extension method if I have cause to do this more often!
frou
A: 

This seems pretty straight-forward ...

for( int i = 0; i < n; i++ ) { lst.Add( thingToAdd ); }

:D

JP Alioto
I know how to do it. I said shortest.
frou
I wasn't one to downvote you, btw. Easy mistake given I didn't say it in the title. Updated it :)
frou
np ... I wonder what you definition of shortest is? Minified?
JP Alioto
Creating and populating in one line, I guess!
frou
Where does lst come from? :p
frou
It's lists all the way down!
JP Alioto
A: 

Java supports this with a different function:

import java.util.Collections;

List<String> repeatedList = Collections.nCopies(100, "RepeatedElement");
Bruno Bowden 2