Home > Software engineering >  Variable length array of dictionarys in C#
Variable length array of dictionarys in C#

Time:04-06

From this post I can make an array of Dictionaries, using the below:

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

But is there a way to make a variable length array without stating all the dictionaries, something like:

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

I am happy to do this with a List, as I'm aware arrays have to be declared.

CodePudding user response:

If all the slots in the array are to be initialized with empty dictionaries, use a simple for loop:

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

If you truly desire a resizable variable-length collection of dictionaries, consider using a List<Dictionary<int, string>> instead of an array:

// 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>());
  • Related