35

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?

Chris Mantle
  • 6,595
  • 3
  • 34
  • 48
321X
  • 3,153
  • 2
  • 30
  • 42

3 Answers3

43

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();
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • Lol, forgot about this. Thank generics for this! – 321X Aug 29 '11 at 13:06
  • 1
    This code can throw [`NullReferenceException`](http://msdn.microsoft.com/en-us/library/system.nullreferenceexception.aspx)s, because the `kvp.Value` could be `null`. If this is the case, just add the `null` value to the `NameValueCollection`. – Ronald Feb 23 '12 at 09:36
40

And if you like LINQ:

Dictionary to NameValueCollection

return dictionary.Aggregate(new NameValueCollection(),
    (seed, current) => { 
        seed.Add(current.Key, current.Value);
        return seed;
    });

NameValueCollection to Dictionary

(source)

return source.Cast<string>()  
    .ToDictionary(s => s, s => source[s]);
drzaus
  • 24,171
  • 16
  • 142
  • 201
6

try this Extension to Dictionary I hope it's what you wanted:

public static class DictionaryExtensions
{
    public static NameValueCollection ToNameValueCollection<tValue>(this IDictionary<string, tValue> 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.

Random Dev
  • 51,810
  • 9
  • 92
  • 119