c# - Flexible use of IDictionary (with interfaces) -


i'm trying flexibly use idictionary interface in 1 of methods because of limitations regarding conversion (see c# type conversion: explicit cast exists throws conversion error? ), use limited me. i'd know if there workaround.

this concrete problem: have method takes mapping maps every key ienumerable of other keys. takes 1 key input. find closure set/hull of given key regarding mapping:

public static iset<t> getclosureset(t element, idictionary<t, ienumerable<t>> elementtocollectionmap) {     iset<t> closure = new hashset<t>();     closure.add(element);     closure.unionwith(elementtocollectionmap[element]);      int count = 0;     while (count != closure.count)     {         count = closure.count;         foreach (t elem in new hashset<t>(closure))             closure.unionwith(elementtocollectionmap[elem]);     }      return closure; } 

example of such mapping of type idictionary<double, ienumerable<double>>:

1 -> [2, 3, 4] 2 -> [3, 7] 3 -> [3] 4 -> [] // empty enumerable, i.e. array of length 0 5 -> [6] 6 -> [6] 7 -> [] 

if put key 1 , mapping method, [1, 2, 3, 4, 7]: first 1 , image [2, 3, 4] put closure set. images of 1, 2, 3, 4 added well, 7 (as element of image of 2). in next step, images of 1, 2, 3 , 4, 7 added, in there. thus, method ends , returns.

as see, abstract method not care values are. needs values ienumerable<t> able call unionwith.

but want able use method whenever have mapping keys sort of collections of keys!

i have places in code define

idictionary<mytype, hashset<mytype>> foo = new dictionary<mytype, hashset<mytype>>(); 

and

idictionary<mytype, list<mytype>> bar = new dictionary<mytype, list<mytype>>(); 

and need them idictionary<mytype, hashset<mytype>> , idictionary<mytype, list<mytype>> because need functionality of hashset , list other provided ienumerable. later want closures. now, cannot give foo , bar input method - need create new dictionaries them fit type.

any ideas on how solve problem (i not consider "creating new dictionary fit type" solution)?

the best way solve problem make slight change public api. fundamentally getclosureset doesn't need mapping of keys sequence of values key, needs operation of values given key:

public static iset<t> getclosureset(     t element,      func<t, ienumerable<t>> childselector) 

the caller can implement method in number of ways, 1 of performing lookup in dictionary have. makes method more general, allows perform operation on different types of graphs store nodes entirely differently, such "node" objects each have reference collection of children, rather graphs stored in dictionary.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -