c# 2.0 - How to convert Dictionary<string, object> to Dictionary<string, string> in c# -
i have below code in c#
dictionary<string, object> dobject = new dictionary<string, object>();
i want convert dobject
dictionary<string, string>
. how can this?
use todictionary method:
dictionary<string, string> dstring = dobject.todictionary(k => k.key, k => k.value.tostring());
here reuse key original dictionary , convert values strings using tostring method.
if dictionary can contain null values should add null check before performing tostring:
dictionary<string, string> dstring = dobject.todictionary(k => k.key, k => k.value == null ? "" : k.value.tostring());
the reason works dictionary<string, object>
ienumerable<keyvaluepair<string,object>>
. above code example iterates through enumerable , builds new dictionary using todictionary method.
edit:
in .net 2.0 cannot use todictionary method, can achieve same using old-fashioned foreach:
dictionary<string, string> sd = new dictionary<string, string>(); foreach (keyvaluepair<string, object> keyvaluepair in dict) { sd.add(keyvaluepair.key, keyvaluepair.value.tostring()); }
edit2:
if on .net 2.0 , can have null values in dictionary following should safe:
dictionary<string, string> sd = new dictionary<string, string>(); foreach (keyvaluepair<string, object> keyvaluepair in dict) { sd.add(keyvaluepair.key, keyvaluepair.value == null ? "" : keyvaluepair.value.tostring()); }
Comments
Post a Comment