Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add value for Complex Dictionary?

Tags:

c#

dictionary

As i know, the method to add values for dictionary as below.

    Dictionary<string, string> myDict = new Dictionary<string, string>();

    myDict.Add("a", "1");

If I declared "myDictDict" as the style below.

IDictionary<string, Dictionary<string, string>> myDictDict = new Dictionary<string, Dictionary<string, string>>();

myDictDict .Add("hello", "tom","cat"); ?// How to add value here.

thank you.

like image 555
Nano HE Avatar asked Dec 28 '09 03:12

Nano HE


2 Answers

The proper way is like this:

// myDictDict is Dictionary<string, Dictionary<string, string>>
Dictionary<string, string> myDict;
string key = "hello";
if (!myDictDict.TryGetValue(key, out myDict)) {
    myDict = new Dictionary<string, string>();
    myDictDict.Add(key, myDict);
}
myDict.Add("tom", "cat");

This will extract the dictionary corresponding to the key (hello in your example) or create it if necessary and then will add the key/value pair to that dictionary. You could even extract this into an extension method.

static class Extensions {
    public static void AddToNestedDictionary<TKey, TNestedDictionary, TNestedKey, TNestedValue>(
        this IDictionary<TKey, TNestedDictionary> dictionary,
        TKey key,
        TNestedKey nestedKey,
        TNestedValue nestedValue
    ) where TNestedDictionary : IDictionary<TNestedKey, TNestedValue> {
        dictionary.AddToNestedDictionary(
            key,
            nestedKey,
            nestedValue,
            () => (TNestedDictionary)(IDictionary<TNestedKey, TNestedValue>)
                new Dictionary<TNestedKey, TNestedValue>());
    }

    public static void AddToNestedDictionary<TKey, TNestedDictionary, TNestedKey, TNestedValue>(
        this IDictionary<TKey, TNestedDictionary> dictionary,
        TKey key,
        TNestedKey nestedKey,
        TNestedValue nestedValue,
        Func<TNestedDictionary> provider
    ) where TNestedDictionary : IDictionary<TNestedKey, TNestedValue> {
        TNestedDictionary nested;
        if (!dictionary.TryGetValue(key, out nested)) {
            nested = provider();
            dictionary.Add(key, nested);
        }
        nested.Add(nestedKey, nestedValue);
    }
}

I left out guarding against null input to keep the idea clear. Usage:

myDictDict.AddToNestedDictionary(
    "hello",
    "tom",
    "cat",
    () => new Dictionary<string, string>()
);

or

myDictDict.AddToNesteDictionary("hello", "tom", "cat");
like image 88
jason Avatar answered Sep 23 '22 01:09

jason


IDictionary<string,Dictionary<string,string>> myDictDict = new Dictionary<string,Dictionary<string,string>>();
Dictionary<string,string> dict = new Dictionary<string, string>();
dict.Add ("tom", "cat");
myDictDict.Add ("hello", dict);
like image 34
Gonzalo Avatar answered Sep 22 '22 01:09

Gonzalo