1

Is it possible in C# to create a list and name it from a variable or similar?

Let's say I have a list with 10 rows in it:

a, b, c, d, e, f, g, h, i, j

Can I make 10 lists from this list, each having a name like one of the rows?

Something like

List<string> myList = new List<string>();
foreach (var line in myList)
{
    List<string> line = new List<string>();
}

What I want is to make a few lists to store data in, but I won't know the names before the program runs so it needs to generate those dynamically.

3
  • 3
    I don't know if it is possible in C#, but it is generally bad practice. How do you intend to find the variable name later? Usually you store this in a multidimensional array or map. Commented Feb 2, 2016 at 14:57
  • 5
    Variable names should be defined at compile-time, they can't be generated in run-time. Probably you need another data structure, for example Dictionary<string, List<string>> where you can specify name as key to find a list Commented Feb 2, 2016 at 14:58
  • @AndyKorneyev well, in fact variables can be generated in runtime, but that's the topic of different discussion :) Commented Feb 2, 2016 at 15:15

3 Answers 3

7

Sounds like you want a Dictionary of List<string>s:

Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();

foreach (var line in myList)
{
    dict.Add(line, new List<string>());
}

Now you can access each list based on the original string we used for the key:

List<string> aList = dict["a"];
Sign up to request clarification or add additional context in comments.

Comments

3

You could try something like this:

var newList = new Dictionary<string, List<string>>();
foreach (var line in myList)
{
  newList.Add(line, new List<string>());
}

This will give you the data structures in which to store your new data and will allow you to reference them based on the names in the first list.

Comments

1

It seems that you want a Dictionary<String, List<String>> like this:

  var data = myList
    .ToDictionary(line => line, line => new List<string>());

And so you can

check if "variable" exists

  if (data.ContainsKey("z")) {...} 

address "variable"

  data["a"].Add("some value");

add "variable"

  data.Add("z", new List<string>());

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.