0

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
1
  • 1
    And what is the problem? Commented Jan 25, 2022 at 20:57

2 Answers 2

2

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]);
Sign up to request clarification or add additional context in comments.

Comments

1

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.