C#: Convert Dictionary<> to NameValueCollection

321X picture 321X · Aug 29, 2011 · Viewed 23.8k times · Source

How can I convert a Dictionary<string, string> to a NameValueCollection?

The existing functionality of our project returns an old-fashioned NameValueCollection which I modify with LINQ. The result should be passed on as a NameValueCollection.

I want to solve this in a generic way. Any hints?

Answer

Daniel Hilgarth picture Daniel Hilgarth · Aug 29, 2011

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<TKey, TValue>(
    this IDictionary<TKey, TValue> 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();