Brief, maybe a silly question: how do you create memory for n Elements when creating a List <type>? The constructor allows you to specify only the approximate capacity, but without selection.

If you can't do that, then how? I want to allocate memory for n elements for 1 line, using, say, addRange (INumerable ...).

I heard something about single-line users using lambda expressions, can they somehow help here, or are they only used when sorting / selecting elements? Tell me please. Do not kick), although no, better kick :)

PS I also need to allocate memory for the List <List <Type>>, if you can also, write)

  • @Bulson it does not allocate memory for elements, but I want to take after creating an object and write for example list [i] = 5; - Xambey
  • you confuse with an array, when creating a list even with the default constructor, it is immediately “ready to work” - Bulson

1 answer 1

In the constructor, you specify the exact capacity : the number of elements, such that increasing the size of the list to this number does not cause relocation, and therefore is fast. In theory, you should not want to create a list with default values; this is most likely meaningless.

But if you really want, you can

  • like this: new T[n].ToList()
  • or so :

     List<T> list = new List<T>(n); list.AddRange(Enumerable.Repeat(default(T), n)); 
  • or like this: Enumerable.Repeat(default(T), n).ToList() (@VadimOvchinnikov variant from comments)

  • In theory, you should not want to create a list with default values, it is most likely meaningless. It would be acceptable, I think, specifically in my case, the number of elements is not large - Xambey
  • Good! What you need), thanks - Xambey
  • @Xambey: The default value is usually meaningless, as soon as you have the desired value, you can add it at this point. - VladD
  • @Xambey: Please! Glad that helped. - VladD
  • @VladD I have little sense in this: "You shouldn't want to create a list with default values ​​...", and why should I want to specify the exact size all the time? - Bulson