How can I convert a Dictionary
to a NameValueCollection
?
The existing functionality of our project returns an old-fashion
try this Extension to Dictionary I hope it's what you wanted:
public static class DictionaryExtensions
{
public static NameValueCollection ToNameValueCollection(this IDictionary dictionary)
{
var collection = new NameValueCollection();
foreach(var pair in dictionary)
collection.Add(pair.Key, pair.Value.ToString());
return collection;
}
}
use like
var nvc = myDict.ToNameValueCollection();
note: I have constrained the key to be string because I didn't want to overgeneralize - of course you can change this with a generic type and .ToString() for the key too.