How can I convert a Dictionary
to a NameValueCollection
?
The existing functionality of our project returns an old-fashion
Why not use a simple foreach
loop?
foreach(var kvp in dict)
{
nameValueCollection.Add(kvp.Key.ToString(), kvp.Value.ToString());
}
This could be embedded into an extension method:
public static NameValueCollection ToNameValueCollection(
this IDictionary dict)
{
var nameValueCollection = new NameValueCollection();
foreach(var kvp in dict)
{
string value = null;
if(kvp.Value != null)
value = kvp.Value.ToString();
nameValueCollection.Add(kvp.Key.ToString(), value);
}
return nameValueCollection;
}
You could then call it like this:
var nameValueCollection = dict.ToNameValueCollection();