Dictionary Dictionary Extension Method

I am 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 still have:

  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 he doesn’t like the compiler. Statement:

 items.LeafDictionaryAdd(longKey, intKey, someTypeValue); 

gives me a type inference error.

For approval:

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

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

What am I doing wrong?

+4
source share
4 answers

Some inventive common use; -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); } 
+8
source

Try using a specific type:

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

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

+2
source

I guess this is the problem of covariance / contravariance. Your method signature expects IDictionary IDcitionaries, but you pass it an IDictionary dictionary. Try using a specific dictionary instead in your method signature for the internal dictionary.

+2
source

If you specify IDictionary in the parameter list for the extension method, then your elements will not match this.

Or change the extension to

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

OR Try and drop your items in

 ((IDictionary<long, IDictionary<int, YourType>>)items).LeafDictionaryAdd(l, i, o); 
+1
source

All Articles