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

本文关键字:创建 数组 字典 循环 for | 更新日期: 2023-09-27 17:56:07

我正在尝试使用 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>();
}

我正在尝试使用存储在名称数组中的名称来迭代创建数组。Visual Studio不接受"构建",因为它已经声明过了。任何建议将不胜感激。谢谢!

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

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;

你可以这样尝试

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

干杯

如果你只是想做一本字典,然后把东西放进去:

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