Search code examples
c#keyvaluepairnamevaluecollection

How can I convert a NameValueCollection to a KeyValuePair


I want to convert a NameValueCollection to a KeyValuePair. Is there a way to do this easily for just a single value in a NameValueCollection?

I have this right now but it seems kind of verbose:

private KeyValuePair<string, string> GetEtagHeader(NameValueCollection collection)
{
    var etagValue = collection.Get(HttpRequestHeader.IfMatch.ToString());

    return new KeyValuePair<string, string>(HttpRequestHeader.IfMatch.ToString(), etagValue);
}

Solution

  • I'm not sure how much shorter you can get it.

    One possibility is to put the Get in where you create the KeyValuePair

    private static KeyValuePair<string, string> GetEtagHeader(NameValueCollection collection)
    {
        string key = HttpRequestHeader.IfMatch.ToString();
        return new KeyValuePair(key, collection.Get(key));
    }
    

    That should serve your case. I'd go a step further and split it into 2 methods - one for your specific case and one generic helper.

    private static KeyValuePair<string, string> GetEtagHeader(NameValueCollection collection)
    {
        return ToKeyValuePair(HttpRequestHeader.IfMatch.ToString(), collection);
    }
    
    private static KeyValuePair<string, string> ToKeyValuePair(string key, NameValueCollection collection)
    {
        return new KeyValuePair(key, collection.Get(key));
    }