Fill List<int> with default values? [duplicate]

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.


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

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();

Yes

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

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]);
    }