简体   繁体   中英

Having a new list<> in each for loop iteration

I am trying to having a new list added on every for loop iteration. I have the following code:

for (int i = 0; i < torni.Length; i++)
{
    List<string> torni+i = // STUCK HER
}

Listnames should be like torni0, torni1, torni2 ......

Would really appreciate your assistance. Thanks!!

One way of doing this that would be slightly different would be to make a list of lists and then each index would be a discrete list.

You can't dynamically generate variable names in c#

like this:

tornis = new List<List<String>>()
for (int i = 0; i < torni.Length; i++)
{
    tornis.append(new List<String>())
}

Alternatively as DanH Points out a dictionary of lists

tornis = new Dictionary<String,List<String>()
for (int i = 0; i < torni.Length; i++)
{
    tornis.add("torni" + i, new List<String>())
}

This will give you a dictionary with the keys of the convention you want and a list of lists.

If you need each list only for the duration of a single loop iteration, then you don't need different list names:

for (int i = 0; i < torni.Length; i++)
{
    List<string> temporaryList = new List<string>();

    // use the list here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM