Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method for Dictionary of Dictionaries

I'm trying to write an extension method to insert data into a dictionary of dictionaries defined as follows:

items=Dictionary<long,Dictionary<int,SomeType>>()

What I have so far is:

    public static void LeafDictionaryAdd<TKEY1,TKEY2,TVALUE>(this IDictionary<TKEY1,IDictionary<TKEY2,TVALUE>> dict,TKEY1 key1,TKEY2 key2,TVALUE value)
    {
        var leafDictionary = 
            dict.ContainsKey(key1) 
                ? dict[key1] 
                : (dict[key1] = new Dictionary<TKEY2, TVALUE>());
        leafDictionary.Add(key2,value);
    }

but the compiler doesn't like it. The statement:

items.LeafDictionaryAdd(longKey, intKey, someTypeValue);

gives me a type inference error.

For the statement:

items.LeafDictionaryAdd<long, int, SomeType>(longKey, intKey, someTypeValue);

I get "...does not contain a definition for... and the best extension method overload has some invalid arguments.

What am I doing wrong?

like image 415
spender Avatar asked Dec 13 '22 04:12

spender


2 Answers

Some inventive generic usage ;-p

class SomeType { }
static void Main()
{
    var items = new Dictionary<long, Dictionary<int, SomeType>>();
    items.Add(12345, 123, new SomeType());
}

public static void Add<TOuterKey, TDictionary, TInnerKey, TValue>(
        this IDictionary<TOuterKey,TDictionary> data,
        TOuterKey outerKey, TInnerKey innerKey, TValue value)
    where TDictionary : class, IDictionary<TInnerKey, TValue>, new()
{
    TDictionary innerData;
    if(!data.TryGetValue(outerKey, out innerData)) {
        innerData = new TDictionary();
        data.Add(outerKey, innerData);
    }
    innerData.Add(innerKey, value);
}
like image 181
Marc Gravell Avatar answered Dec 15 '22 19:12

Marc Gravell


Try to use a concrete type:

public static void LeafDictionaryAdd<TKEY1,TKEY2,TVALUE>(this IDictionary<TKEY1, Dictionary<TKEY2,TVALUE>> dict,TKEY1 key1,TKEY2 key2,TVALUE value)

see the Dictionary<TKEY2,TVALUE> instead of IDictionary<TKEY2,TVALUE>

like image 21
tanascius Avatar answered Dec 15 '22 19:12

tanascius