1

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);
}
DannyD
  • 2,732
  • 16
  • 51
  • 73

3 Answers3

0

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));
}
pamcevoy
  • 1,136
  • 11
  • 15
  • These methods should be `static` since they don't reference any members of the enclosing class. Better yet, they could be extension methods with a `this NameValueCollection collection` parameter. – TypeIA Nov 20 '18 at 22:44
0

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));
}
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
0

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());
}
John Wu
  • 50,556
  • 8
  • 44
  • 80