1

I have a list of names in an array and i would like to use these names to assign them to new lists like bellow:

    var list = new string[]{"bot1","bot2","bot3"};  
    List<string> list[0] = new List<string>();  

but i am getting the error: a local variable or function named 'list' is already defined in this scope.

is there a work around !!? your input will be greatly appreciated.

Mehrdad_gh
  • 33
  • 2
  • 11
  • You can't define more than one variable as the same name. Just change the second variable to some other name like `name`. – John Odom Apr 21 '17 at 21:39
  • 1
    Possible duplicate of [Create dynamic variable name](http://stackoverflow.com/questions/20857773/create-dynamic-variable-name) – Usman Apr 21 '17 at 21:41
  • @JohnOdom do you mean instead of list[0], i should use name (or what ever) !!? – Mehrdad_gh Apr 21 '17 at 21:42
  • @Usman i saw that one but from the looks of it, that is for changing the variable not assigning it to something else, but thanks anyway. – Mehrdad_gh Apr 21 '17 at 21:44

2 Answers2

3

I think you can store your bots in dictionary:

var bots = new Dictionary<string,List<string>>();
bots[name] = new List<string>();
bots[name].Add("some str");
gabba
  • 2,815
  • 2
  • 27
  • 48
  • @Mehrdad_gh, you are welcome, you also might want to change type of value structure to some class – gabba Apr 21 '17 at 22:01
  • yes i am using a class for the list but couldn't figure out your solution and it helped greatly, thanks again – Mehrdad_gh Apr 21 '17 at 22:13
0

If you only need a integer as key than you can also use this solution.

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

list.Add(new List<string>{ {"A"} });

list[0][0] = "..";
  • 1
    Consider adding additional details that explain how and why this works. – David L Apr 22 '17 at 04:07
  • @Wolfram Wisser, Your solutions good when we needs to access bots by index, but when we have just name we must scan whole list to access. O(n) complexity. Dictionary gave as O(1) access complexity. – gabba Apr 22 '17 at 08:37