c# - Copy key values from NameValueCollection to Generic Dictionary -
trying copy values existing namevaluecollection object dictionary. have following code below seems add not accept keys , values strings
idictionary<tkey, tvalue> dict = new dictionary<tkey, tvalue>(); public void copyfromnamevaluecollection (namevaluecollection a) { foreach (var k in a.allkeys) { dict.add(k, a[k]); } }
note: namevaluecollection contains string keys , values , want provide here method allow copying of generic dictionary.
it doesn't make sense use generics here since can't assign string
s arbitrary generic type:
idictionary<string, string> dict = new dictionary<string, string>(); public void copyfrom(namevaluecollection a) { foreach (var k in a.allkeys) { dict.add(k, a[k]); } }
although should create method create new dictionary instead:
public static idictionary<string, string> todictionary(this namevaluecollection col) { idictionary<string, string> dict = new dictionary<string, string>(); foreach (var k in col.allkeys) { dict.add(k, col[k]); } return dict; }
which can use like:
namevaluecollection nvc = // var dictionary = nvc.todictionary();
if want general way of converting strings in collection required key/value types, can use type converters:
public static dictionary<tkey, tvalue> todictionary<tkey, tvalue>(this namevaluecollection col) { var dict = new dictionary<tkey, tvalue>(); var keyconverter = typedescriptor.getconverter(typeof(tkey)); var valueconverter = typedescriptor.getconverter(typeof(tvalue)); foreach(string name in col) { tkey key = (tkey)keyconverter.convertfromstring(name); tvalue value = (tvalue)valueconverter.convertfromstring(col[name]); dict.add(key, value); } return dict; }
Comments
Post a Comment