12

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.

Hari
  • 1,561
  • 4
  • 17
  • 26
  • 1
    That's pretty compact. And maybe yes, there's a "smooth" or fancy way to do it, but what you've written is clear to even novice developers. Good enough! – James Cronen Oct 08 '13 at 01:57
  • So, maybe a duplicate of this: http://stackoverflow.com/questions/2032411/is-there-a-way-to-fill-a-collection-using-a-linq-expression – James Cronen Oct 08 '13 at 01:57
  • 1
    possible duplicate of [Auto-initializing C# lists](http://stackoverflow.com/questions/1104457/auto-initializing-c-sharp-lists) – CodeNaked Oct 08 '13 at 02:09
  • possible duplicate of [Fill List with default values?](http://stackoverflow.com/questions/3363940/fill-listint-with-default-values) – Qantas 94 Heavy Apr 14 '14 at 09:14

3 Answers3

17

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

var a = Enumerable.Repeat(0, n).ToList();
Khan
  • 17,904
  • 5
  • 47
  • 59
  • 1
    It's worth calling out that the `Enumerable` methods have the benefit of being lazy if you don't invoke the `ToList` up front. – Preston Guillot Oct 08 '13 at 02:04
7

You can use the Enumerable.Repeat generator:

var list = new List<int>(Enumerable.Repeat(0, n));
porges
  • 30,133
  • 4
  • 83
  • 114
2
List<int> x = Enumerable.Repeat(value, count).ToList();
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
John DeLeon
  • 305
  • 1
  • 3