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?
Well, you can ask LINQ to do the looping for you:
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:
That will do a block copy from the array into the list, which will probably be more efficient than the looping required by
ToList.