How can I convert a NameValueCollection to a KeyValuePair

1.7k Views Asked by At

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);
}
3

There are 3 best solutions below

1
On BEST ANSWER

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));
}
2
On

It would be less verbose if you put HttpRequestHeader.IfMatch.ToString() into a temp variable and instead inline the temp etagValue:

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

If it were me, I'd define an extension method like this one:

public static class ExtensionMethods
{
    static public KeyValuePair<string,string> GetPair(this NameValueCollection source, string key)
    {
        return new KeyValuePair<string, string>
        (
            key,
            source.Get(key)
        );
    }
}

Then you can just write your original code like this:

private KeyValuePair<string, string> GetEtagHeader(NameValueCollection collection)
{
    return collection.GetPair(HttpRequestHeader.IfMatch.ToString());
}