-1

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.

JackNapier
  • 318
  • 4
  • 14

1 Answers1

4

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>());
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • That seems great thanks Mathias! For the second one, I can't seem to do normal List functions like WriteLine on it - something like matrix.ToList().ForEach(x => Console.WriteLine(x.Key)); Can you give me an idea of the syntax? – JackNapier Apr 05 '22 at 23:20
  • @JackNapier `Dictionary` does not have a `Key` property (the individual _entries_ of each dictionary do). If you want the keys from all entries in all dictionaries in the list: `matrix.SelectMany(dictionary => dictionary.Keys).ForEach(k => Console.WriteLine(k))` – Mathias R. Jessen Apr 05 '22 at 23:28
  • Sorry to bug you Mathias, that's still giving me an error: 'System.Collections.Generic.IEnumerable' does not contain a definition for 'ForEach' and no extension method 'ForEach' accepting a first argument of type 'System.Collections.Generic.IEnumerable' – JackNapier Apr 05 '22 at 23:39
  • @JackNapier My bad, you'll need a `ToList()` call after `SelectMany()`. (That being said, I can't recall ever using `List.ForEach()`, seems a bit of an antipattern - just use a regular loop) :) – Mathias R. Jessen Apr 05 '22 at 23:42