Fill List<int> with default values?

C#List

C# Problem Overview


> Possible Duplicate:
> Auto-Initializing C# Lists

I have a list of integers that has a certain capacity that I would like to automatically fill when declared.

List<int> x = new List<int>(10);

Is there an easier way to fill this list with 10 ints that have the default value for an int rather than looping through and adding the items?

C# Solutions


Solution 1 - C#

Well, you can ask LINQ to do the looping for you:

List<int> x = Enumerable.Repeat(value, count).ToList();

It's unclear whether by "default value" you mean 0 or a custom default value.

You can make this slightly more efficient (in execution time; it's worse in memory) by creating an array:

List<int> x = new List<int>(new int[count]);

That will do a block copy from the array into the list, which will probably be more efficient than the looping required by ToList.

Solution 2 - C#

int defaultValue = 0;
return Enumerable.Repeat(defaultValue, 10).ToList();

Solution 3 - C#

if you have a fixed length list and you want all the elements to have the default value, then maybe you should just use an array:

int[] x  = new int[10];

Alternatively this may be a good place for a custom extension method:

public static void Fill<T>(this ICollection<T> lst, int num)
{
    Fill(lst, default(T), num);
}

public static void Fill<T>(this ICollection<T> lst, T val, int num)
{
    lst.Clear();
    for(int i = 0; i < num; i++)
        lst.Add(val);
}

and then you can even add a special overload for the List class to fill up to the capacity:

public static void Fill<T>(this List<T> lst, T val)
{
    Fill(lst, val, lst.Capacity);
}
public static void Fill<T>(this List<T> lst)
{
    Fill(lst, default(T), lst.Capacity);
}

Then you can just say:

List<int> x  = new List(10).Fill();

Solution 4 - C#

Yes

int[] arr = new int[10];
List<int> list = new List<int>(arr);

Solution 5 - C#

var count = 10;
var list = new List<int>(new int[count]);

ADD

Here is generic method to get the list with default values:

    public static List<T> GetListFilledWithDefaulValues<T>(int count)
    {
        if (count < 0)
            throw new ArgumentException("Count of elements cannot be less than zero", "count");

        return new List<T>(new T[count]);
    }

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
QuestionBLGView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#Tim RobinsonView Answer on Stackoverflow
Solution 3 - C#lukeView Answer on Stackoverflow
Solution 4 - C#Itay KaroView Answer on Stackoverflow
Solution 5 - C#Eugene CheverdaView Answer on Stackoverflow