我正在尝试使用for循环在C#中创建多个数组/字典

时间:2016-07-08 15:41:45

标签: c# arrays for-loop dictionary

我正在尝试使用for循环在C#中创建多个数组/字典。我可以单独声明它们,但它不干净。

这是我的代码:

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>();
}

我正在尝试使用存储在names数组中的名称来迭代创建数组。 Visual Studio不接受&#34;构建&#34;因为它已经宣布。任何建议将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:5)

在C#中没有办法创建动态命名的局部变量。

也许你想要一本字典词典?

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;

答案 1 :(得分:1)

你可以这样试试

        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"];

干杯

答案 2 :(得分:1)

如果你只是想制作一本字典,并把东西放进去:

        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);
        }