Search code examples
c#constructornested-listslist-initialization

C# How to call the inner list constructor inorder to define capacity


I would like to access the inner list constructor inorder to define capacity, how could i achieve this? This is what i have: this will initialize the outer list to 20 elements.

public List<List<(int x, int y)>> coordinatesForHorizontalShips = new List<List<(int x, int y)>>(20);

From microsoft:

https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.-ctor?view=net-6.0 List(Int32) Initializes a new instance of the List class that is empty and has the specified initial capacity.

C#

Copy
public List (int capacity);
Parameters
capacity
Int32
The number of elements that the new list can initially store.

Solution

  • This is how to initialize 20 outer lists with each having 1_000 capacity:

    public List<List<(int x, int y)>> coordinatesForHorizontalShips =
        Enumerable.Range(0, 20).Select(x => new List<(int x, int y)>(1000)).ToList();