locked
How to create dynamic object of lists. RRS feed

  • Question

  • User1047891237 posted

    Hi All,

    I have a requirement to generate 10 lists of string type where object generation for every list should be in a dynamic way. there I need to create the dynamic object.can we create that in c#. I have tried like this

    for (int i = 1; i <= 10; i++)
    {

    string obj = i.ToString();
    List<string> obj = new List<string>();
    }

    But it gives error

    "Error CS0128 A local variable named 'obj' is already defined in this scope ConsoleApplication12 C:\Users\sdfas\Documents\Visual Studio 2015\Projects\ConsoleApplication12\ConsoleApplication12\Program.cs 40 Active"

    Thursday, February 20, 2020 10:12 AM

Answers

  • User288213138 posted

    Hi anupamdev,

    I wanted to generate 10 lists at once

    If you want to create dynamic list name, you can try to below code, create Dictionary<string, List<string>>.

    var dict = new Dictionary<string, List<string>>();
    
    dict["x1"] = new List<string>();

    You can replace "x1" with variable.

    Best regards,

    Sam

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, February 25, 2020 8:25 AM

All replies

  • User288213138 posted

    Hi anupamdev,

    I have a requirement to generate 10 lists of string type where object generation for every list should be in a dynamic way. there I need to create the dynamic object.can we create that in c#. I have tried like this

    for (int i = 1; i <= 10; i++)
    {

    string obj = i.ToString();
    List<string> obj = new List<string>();
    }

    But it gives error

    "Error CS0128 A local variable named 'obj' is already defined in this scope ConsoleApplication12 C:\Users\sdfas\Documents\Visual Studio 2015\Projects\ConsoleApplication12\ConsoleApplication12\Program.cs 40 Active"

    In your code you have defined 2 obj, so there will be this error.

    Do you want to generate 10 lists at once? if so, I suggest you write 10 lists directly.

    If not, please post more details information about your requirement.

    Best regards,

    Sam

    Friday, February 21, 2020 7:08 AM
  • User1047891237 posted

    Thank you samwu. I wanted to generate 10 lists at once. so I will write 10 lists directly.

    Friday, February 21, 2020 9:07 AM
  • User288213138 posted

    Hi anupamdev,

    I wanted to generate 10 lists at once

    If you want to create dynamic list name, you can try to below code, create Dictionary<string, List<string>>.

    var dict = new Dictionary<string, List<string>>();
    
    dict["x1"] = new List<string>();

    You can replace "x1" with variable.

    Best regards,

    Sam

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, February 25, 2020 8:25 AM
  • User1047891237 posted

    Thank you samwu. I have tried the same. it works for me.

    Tuesday, February 25, 2020 10:16 AM