Shortest way to create a List<T> of a repeated element
18,539
Solution 1
Try the following
var l = Enumerable.Repeat('x',5).ToList();
Solution 2
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);
Solution 3
This seems pretty straight-forward ...
for( int i = 0; i < n; i++ ) { lst.Add( thingToAdd ); }
:D
Related videos on Youtube
Author by
xyz
Updated on April 19, 2022Comments
-
xyz about 2 years
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? -
xyz almost 15 yearsI know how to do it. I said shortest.
-
xyz almost 15 yearsI wasn't one to downvote you, btw. Easy mistake given I didn't say it in the title. Updated it :)
-
JP Alioto almost 15 yearsnp ... I wonder what you definition of shortest is? Minified?
-
typpo almost 7 yearsIf you know the list length, set it during construction: var list = new List<MyObject>(5);
-
user1234567 almost 5 years#Note: for reference type it results in a list of 5 references to same instance. E.g.:
var l = Enumerable.Repeat(new SomeRefType(),5).ToList();
will create single instance ofSomeRefType
& populate list with 5 references to this instance.