dimitris93
dimitris93

Reputation: 4273

How to initialize nested list Capacities?

I want to make a list of lists in C#, the outer list must have a capacity of 5 and each inner a capacity of 100. How to initialize it ?

This code does not compile:

List<List<int>> outer = new List<List<int>>(5);
for (int i = 0; i < 5; i++)
{
    outer[i].Add(new List<int>(100));
}

Edit: I didn't want the lists to change size on runtime, cause memory allocation destroys performance and this is for a mobile game

Upvotes: 2

Views: 3389

Answers (1)

Matthew Haugen
Matthew Haugen

Reputation: 13286

Your code has a minor typo.

List<List<int>> outer = new List<List<int>>(5);
for (int i = 0; i < 5; i++)
{
      // vv here //
    outer[i].Add(new List<int>(100));
}

You're trying to add the list to itself, which, of course, doesn't work. If you drop that [i], that should solve your problem.

List<List<int>> outer = new List<List<int>>(5);
for (int i = 0; i < 5; i++)
{
    outer.Add(new List<int>(100));
}

That said, if you don't have a strict need for the outer capacity to be set, I'd suggest doing this with LINQ.

List<List<int>> outer = Enumerable.Range(0, 5).Select(c => new List<int>(100)).ToList();

And if you do need a capacity, an array might be a better fit for the outer collection.

Upvotes: 4

Related Questions