user2138160
user2138160

Reputation: 279

How to populate a dictionary of dictionaries of dictionaries?

I am trying to populate a dictionary of dictionaries of dictionaries. However when I try to populate my third dictionary I get the follow error below. How would I populate my second dictionary without getting an error?

The best overloaded method match for 'System.Collections.Generic.Dictionary<string,System.Collections.Generic.Dictionary<string,
 System.Collections.Generic.List<string>>>.this[string]' has some invalid arguments 


//code

ClientsData.Add(new MapModel.ClientInfo { Id = IDCounter, Doctors = new Dictionary<string, Dictionary<string,List<string>>>() });

ClientsData[0].Doctors.Add(Reader["DocID"].ToString(), new Dictionary<string,List<string>>());

ClientsData[0].Doctors[0].Add("Name", new List<string>(){ Reader["DocName"].ToString()});//Error occurs here 

Upvotes: 0

Views: 779

Answers (2)

Tony
Tony

Reputation: 7445

If you want to use tripple dictonaries you can use the following snippet:

var dict = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();

dict["level-one"] = new Dictionary<string, Dictionary<string, string>>();
dict["level-one"]["level-two"] = new Dictionary<string, string>();
dict["level-one"]["level-two"]["level-three"] = "hello";

Console.WriteLine(dict["level-one"]["level-two"]["level-three"]);

Or you can make your own wrapper like this:

public class TrippleDictionary<TKey, TValue> 
{
    Dictionary<TKey, Dictionary<TKey, Dictionary<TKey, TValue>>> dict = new Dictionary<TKey, Dictionary<TKey, Dictionary<TKey, TValue>>>();

    public TValue this [TKey key1, TKey key2, TKey key3] 
    {
        get 
        {
            CheckKeys(key1, key2, key3);
            return dict[key1][key2][key3]; 
        }
        set
        {
            CheckKeys(key1, key2, key3);
            dict[key1][key2][key3] = value;
        }
    }

    void CheckKeys(TKey key1, TKey key2, TKey key3)
    {
        if (!dict.ContainsKey(key1))
            dict[key1] = new Dictionary<TKey, Dictionary<TKey, TValue>>();

        if (!dict[key1].ContainsKey(key2))
            dict[key1][key2] = new Dictionary<TKey, TValue>();

        if (!dict[key1][key2].ContainsKey(key3))
            dict[key1][key2][key3] = default(TValue);
    }
}    

And use it like this:

var tripple = new TrippleDictionary<string, string>();
tripple["1", "2", "3"] = "Hello!";

Console.WriteLine(tripple["1", "2", "3"]);

See Demo

Upvotes: 1

Alden
Alden

Reputation: 6713

To access a dictionary like that you need to use a key, which in your case is a string:

ClientsData[0].Doctors[Reader["DocID"].ToString()].Add("Name", new List<string>(){ Reader["DocName"].ToString()});

Upvotes: 1

Related Questions