Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

list

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?

like image 564
BLG Avatar asked Jul 29 '10 15:07

BLG


2 Answers

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.

like image 187
Jon Skeet Avatar answered Oct 26 '22 06:10

Jon Skeet


int defaultValue = 0; return Enumerable.Repeat(defaultValue, 10).ToList(); 
like image 20
Tim Robinson Avatar answered Oct 26 '22 06:10

Tim Robinson