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

C#.Net.Net 3.5List

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

Try the following

var l = Enumerable.Repeat('x',5).ToList();

Solution 2 - C#

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 - C#

This seems pretty straight-forward ...

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

:D

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionxyzView Question on Stackoverflow
Solution 1 - C#JaredParView Answer on Stackoverflow
Solution 2 - C#Andy_VulhopView Answer on Stackoverflow
Solution 3 - C#JP AliotoView Answer on Stackoverflow