Search code examples
c#namevaluecollection

C#: Convert Dictionary<> to NameValueCollection


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?


Solution

  • 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();