简体   繁体   English

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

[英]I am trying to create multiple arrays/dictionaries in C# using a for loop

I am trying to create multiple arrays/dictionaries in C# using a for loop. 我正在尝试使用for循环在C#中创建多个数组/字典。 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. Visual Studio不接受已经声明的“构建”。 Any suggestion would be greatly appreciated. 任何建议将不胜感激。 Thank you! 谢谢!

There's not a way in C# to create dynamically-named local variables. C#中没有办法创建动态命名的局部变量。

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;

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 干杯

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM