Reputation: 1907
I am trying to create multiple arrays/dictionaries in C# using a for loop. I can declare them individually, but it's not clean.
Here is my code:
string[] names = ["dSSB", "dGEN", "dLYM", "dLUD", "dGGC", "dMAC", "dMMB"];
for (int i = 0; i <= names.Length; i++)
{
string building = names[i];
Dictionary<long, int> building = new Dictionary<long, int>();
}
I am trying to use the names stored in the names array to iteratively create arrays. Visual Studio doesn't accept "building" as it is already declared. Any suggestion would be greatly appreciated. Thank you!
Upvotes: 0
Views: 824
Reputation: 27
If you're simply trying to make a dictionary, and put stuff in it:
Dictionary<int, string> buildings = new Dictionary<int, string>();
string[] names = { "dSSB", "dGEN", "dLYM", "dLUD", "dGGC", "dMAC", "dMMB" };
for (int i = 0; i < names.Length; i++)
{
buildings.Add(i, names[i]);
}
foreach (KeyValuePair<int, string> building in buildings)
{
Console.WriteLine(building);
}
Upvotes: 1
Reputation: 309
You can try it like this
string[] names = {"dSSB", "dGEN", "dLYM", "dLUD", "dGGC", "dMAC", "dMMB"};
Dictionary<string, Dictionary<long, int>> buildings = new Dictionary<string, Dictionary<long, int>>();
for (int i = 0; i <= names.Length -1; i++)
{
buildings[names[i]] = new Dictionary<long, int>();
buildings[names[i]].Add(5L, 55);
}
//Here you can get the needed dictionary from the 'parent' dictionary by key
var neededDictionary = buildings["dSSB"];
Cheers
Upvotes: 1
Reputation: 152566
There's not a way in C# to create dynamically-named local variables.
Perhaps you want a dictionary of dictionaries?
string[] names = ["dSSB", "dGEN", "dLYM", "dLUD", "dGGC", "dMAC", "dMMB"];
var buildings = new Dictionary<string,Dictionary<long, int>>();
for (int i = 0; i <= names.Length; i++) {
buildings[names[i]] = new Dictionary<long, int>();
}
//... meanwhile, at the Hall of Justice ...
// reference the dictionary by key string
buildings["dSSB"][1234L] = 5678;
Upvotes: 5