0

I am dealing with Array of Dictionaries and this SO Post is really helpful to achieve what I want so far.

But, now I want to initialize Dictionary for an array index based on the output of code.

I have a Dictionary<int,string>, where I am storing a Id as Key. I am having Array of 10 dictionaries as follows:

Dictionary<int, string>[] matrix = new Dictionary<int, string>[10];

So, based on the value of (Id%10), i want to store that record in a respective array. For i.e., if id= 12, I want to store it in matrix[2]. If id = 15, i want to store it in matrix[5].

Now,question is, how to check each time whether a dictionary is initialized for a particular index or not. If yes, than add the record to the dictionary else initialize the instance and then add the record to Dictionary.

Something like following:

if {} // if dict with id%10 is initialized then
{
    matrix[id%10].Add();
}
else
{
    matrix[id%10] = new Dictionary<int,string>();
    matrix[id%10].Add();
}

Edit: I know i can initialize all first using loop, but I want to initialize only when it's necessary.

Harshil Doshi
  • 3,497
  • 3
  • 14
  • 37

1 Answers1

2
    Dictionary<int, string>[] matrix = new Dictionary<int, string>[10];
    int id = 0; // Number here
    int index = id % 10;

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

    int key = 0; // key you want to insert

    if (matrix[index].ContainsKey(key))
    {
        // Dictionary already has this key. handle this the way you want
    }
    else
    {
        matrix[index].Add(0, ""); // Key and value here
    }
danish
  • 5,550
  • 2
  • 25
  • 28
  • ok. That's just too easy and really embarrassing for me. Thank you. – Harshil Doshi May 02 '18 at 09:54
  • 1
    @HarshilDoshi No problem. Note that key check is also needed here. Without that you might end up getting exceptions – danish May 02 '18 at 10:07
  • 1
    @mjwills why? We just want to see if a key exists or not. – danish May 02 '18 at 11:13
  • 2
    The advantage of `TryGetValue` is that if `// Dictionary already has this key. handle this the way you want` needs to access the object stored in the `Dictionary` it can do so without another hash lookup. – mjwills May 02 '18 at 11:16
  • 1
    Ah in that case. Sure. Only if we need the existing value associated with the key though. – danish May 02 '18 at 11:18