Dictionary set value with dynamic keys

Hello all,

Currently I’m saving my json values locally in a Dictionary. I want to write a function that takes in an array of keys, and a value, and saves it to the root Dictionary. It’s easy to do this if we know the amount of keys, but in my case, I don’t. For example:

// Setting a value with three keys
public void SetValue(T value, string key1, string key2, string key3)
{
    ((m_saveData[key1] as Dictionary<string, object>)[key2] as Dictionary<string, object>)[key3] = value;
}

// Setting a value with four keys
public void SetValue(T value, string key1, string key2, string key3, string key4)
{
    (((m_saveData[key1] as Dictionary<string, object>)[key2] as Dictionary<string, object>)[key3] as Dictionary<string, object>)[key4] = value;
}

// Setting a value with x keys
public void SetValue(T value, params string[] keys)
{
    // How do?
}

Has anyone done something like this before, or know how one would do it?

Under the hood, a Dictionary<> is implemented as a hash table, so the problem isn’t about the keys, it is about the hash code. The simplest means I can think of would be to create 1 string key, but concatenate the variable number of sub-keys prior to insertion, possibly with a separator character between the keys so you can parse them apart.


An alternative is to create a struct or class for which you provide a hash function suitable for the Dictionary, which computes the hash based on whatever list of strings the object happens to have.