polosek
polosek

Reputation: 33

C# - Creating multiple lists based on int in Console

I want to create multiple lists from a given size. Imagining it could look something like this :

int Size = int.Parse(Console.ReadLine());
for (int i = 0; i < Size; i++)
{
    List<string> ListName + i = new List<string>();
}

So for example if size = 5 I'd get 5 lists :

ListName0
ListName1
ListName2
ListName3
ListName4

Upvotes: 0

Views: 138

Answers (2)

Serge
Serge

Reputation: 43870

the common way is to use a dictionary

    var list = new Dictionary<string, List<string>>();
    int size = int.Parse(Console.ReadLine());
    for (int i = 0; i < size; i++)
            list["Name"+i.ToString()] = new List<string>();

how to use

    list["Name1"].Add( "hello world");

Upvotes: 1

Austin
Austin

Reputation: 2265

Create a container for the lists outside your loop:

int Size = int.Parse(Console.ReadLine());

List<List<string>> listContainer = new List<List<string>>();

for (int i = 0; i < Size; i++)
{
    listContainer.Add(new List<string>());
}

You can access them via the index of the container object. For example listContainer[0] would be the first list<string> in the container.

Here is an example of accessing one of the lists and then accessing a value from said list:

int Size = int.Parse(Console.ReadLine());

List<List<string>> listContainer = new List<List<string>>();

for (int i = 0; i < Size; i++)
{
    listContainer.Add(new List<string>());
}

listContainer[0].Add("Hi");
Console.WriteLine(listContainer[0][0]);

Upvotes: 2

Related Questions