c# - iterate .net dictionary as object -
i have interesting problem. need write general (i'd use word "generic" conflict i'm after) routine can hand instance of dictionary object instance , iterate on content of said object dictionary , return content literal values. difficulty lies in method parameter of type "object", not dictionary.
what need , can't figure out how do, way of iterating on dictionary<k, v>
of arbitrary keys , values. easy if know types going in, say, origin of dictionary object object.gettype().getinterfaces() has typeof(idictionary) in results. won't know (and shouldn't need know) dictionary key type or value type.
my current need process dictionary<string, someclass>
;. once list of keys can use foreach on each instance, figure out it's string , proceed there. values it'll instance of class (the class change again, can pass off set of methods extract class, extract properties of class , extract values).
the main point of request obtain method (or 2 or many) allow me iterate on dictionary of unknown types , extract keys , values, without knowing types @ compile time. above dictionary; example, need able pass dictionary. @ moment, i'm not worried edge cases dictionary<tuple<int, string, someotherclass>, someclass>>
or things that, if can start dictionary<string, someclass>;
, can proceed there.
it's getting keys , values out in form can process haven't figured out how yet.
you mentioned have access idictionary<k,v>
interface on object. can use get_keys
, get_values
access keys , values respectively.
also, idictionary<k,v>
derives ienumerable<keyvaluepair<k,v>>
can access list of key-value pairs using for-loop similar lists.
edit - clarification:
idictionary inputasdictionary = input idictionary; if (inputasdictionary != null) { // valid : input dictionary. icollection dictkeys = inputasdictionary.keys; // list of keys icollection dictvalues = inputasdictionary.values; // list of values // iterate on keys for(var dictkey in dictkeys) { console.writeline(dictkey); // print key type dictkeytype = dictkey.gettype(); // type of key if required // ... } // similarly, iterate on values for(var dictvalue in dictvalues) { console.writeline(dictvalue); // print value type dictvaluetype = dictvalue.gettype(); // type of value if required // ... } }
you can using generic dictionary<k,v>
interface, gets lot more complicated types. need call type.generictypearguments , go there. example have shown seems simpler.
Comments
Post a Comment