i'm having problems casting in foreach loop.
i have following code consists of basic object:
public class dbfieldmap { public string fieldname { get; set; } public string fieldvalue { get; set; } public dbfieldmap() { } public dbfieldmap(string fname, string fvalue) { fieldname = fname; fieldvalue = fvalue; } }
a dictionary using above object
public class mappedsqlfields : dictionary<string, dbfieldmap> { public mappedsqlfields() { this.add("firstname", new dbfieldmap()); this.add("lastname", new dbfieldmap()); this.add("email", new dbfieldmap()); etc... } }
another object property based on above object
public class audience : ienumerable { ... public mappedsqlfields audiencesqlmap { get; set; } }
i able loop through audiencesqlmap property , extract values fieldname , fieldvalue properties of dbfieldmap dictionary object i'm receiving following error though @ "foreach" line. i've tried various explicit casts still can't seem able casting work.
foreach (mappedsqlfields item in audience.audiencesqlmap) { //do item.fieldname , item.fieldvalue }
error 49 cannot convert type 'system.collections.generic.keyvaluepair' 'mappedsqlfields'
any appreciated. thank you.
the saga continues
okay, above works everyone's below, i'm having problems casting json equivalent of object original object. i'm receiving same error receiving, have tried various cast statements can think of , it's still gives me grief. i'm missing regarding whole topic.
this works fine:
var json = new javascriptserializer().serialize(audiencesqlmap);
error on line:
this.audiencesqlmap = (mappedsqlfields)new javascriptserializer().deserialize(json,typeof(keyvaluepair<string, dbfieldmap>));
it expects iterating on key/value pair.
modify code use keyvaluepair<string, dbfieldmap>
:
foreach (keyvaluepair<string, dbfieldmap> item in audience.audiencesqlmap)
or, more succinctly, use var
:
foreach (var item in audience.audiencesqlmap) { //do item.fieldname , item.fieldvalue var name = item.value.fieldname; var value = item.value.fieldvalue; ... }
if need values of dictionary though, iterate on those:
foreach (dbfieldmap map in a.audiencesqlmap.values) { var name = map.fieldname; var value = map.fieldvalue; ... }
Comments
Post a Comment