C# 中字典的可变长度数组

Variable length array of dictionarys in C#

this post 我可以使用下面的方法创建一个字典数组:

Dictionary<int, string>[] matrix = new Dictionary<int, string>[] 
{
    new Dictionary<int, string>(),
    new Dictionary<int, string>(),
    new Dictionary<int, string>()
};

但是有没有办法在不声明所有字典的情况下制作可变长度数组,例如:

int amountOfDict = 4;
Dictionary<int, string>[] matrix = new Dictionary<int, string>[] 
{
    //for the amount of amountOfDict, make Dictionaries
};

我很乐意使用列表来执行此操作,因为我知道必须声明数组。

如果要用空字典初始化数组中的所有槽,使用简单的for循环:

// create array of specified size
Dictionary<int, string>[] matrix = new Dictionary<int, string>[amountDict];

// populate each slot in array with a new empty dictionary
for(int i = 0; i < amountDict; i++)
    matrix[i] = new Dictionary<int, string>();

如果您确实需要 可调整大小的 variable-length 字典集合,请考虑使用 List<Dictionary<int, string>> 而不是数组:

// create empty list of dictionaries
List<Dictionary<int, string>> matrix = new List<Dictionary<int, string>>();

// add desired amount of new empty dictionaries to list
for(int i = 0; i < amountDict; i++)
    matrix.Add(new Dictionary<int, string>());