Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a List of given size, all initialized to some value, in C#

Tags:

c#

list

Is there a compact manner in which the following can be done?

List<int> a = new List<int>();

for (int i = 0; i < n; ++i)
   a.Add(0);

i.e., creating a list of n elements, all of value 0.

like image 717
Hari Avatar asked Oct 08 '13 01:10

Hari


3 Answers

Enumberable.Repeat would be the shortest method I can think of:

var a = Enumerable.Repeat(0, n).ToList();
like image 109
Khan Avatar answered Oct 13 '22 20:10

Khan


You can use the Enumerable.Repeat generator:

var list = new List<int>(Enumerable.Repeat(0, n));
like image 7
porges Avatar answered Oct 13 '22 21:10

porges


List<int> x = Enumerable.Repeat(value, count).ToList();
like image 2
John DeLeon Avatar answered Oct 13 '22 21:10

John DeLeon