Search code examples
c#.netnamevaluecollection

Get all values of a NameValueCollection to a string


I have the following code:

string Keys = string.Join(",",FormValues.AllKeys);

I was trying to play around with the get:

string Values = string.Join(",", FormValues.AllKeys.GetValue());

But of course that doesn't work.

I need something similar to get all the values, but I don't seem to find the appropriate code to do the same.

P.S: I do not want to use a foreach loop since that beats the purpose of the first line of code.


Solution

  • var col = new NameValueCollection() { { "a", "b" }, { "1", "2" } }; // collection initializer
    
    var values = col.Cast<string>().Select(e => col[e]); // b, 2
    
    var str = String.Join(",", values );  // "b,2"
    

    Also you can create an extension method:

    public static string Join(this NameValueCollection collection, Func<string,string> selector, string separator)
    {
        return String.Join(separator, collection.Cast<string>().Select(e => selector(e)));
    }
    

    Usage:

    var s = c.Join(e => String.Format("\"{0}\"", c[e]), ",");
    

    Also you can easily convert NameValueCollection to more handy Dictionary<string,string> so:

    public static IDictionary<string,string> ToDictionary(this NameValueCollection col)
    {
        return col.AllKeys.ToDictionary(x => x, x => col[x]);
    }
    

    Gives:

    var d = c.ToDictionary();
    

    As I found using Reflector, NameValueCollection.AllKeys internally performs a loop to gather all te keys, so it seems that c.Cast<string>() is more preferable.