如何将NameValueCollection转换为KeyValuePair

时间:2018-11-20 22:08:50

标签: c# keyvaluepair namevaluecollection

我想将NameValueCollection转换为KeyValuePair。有没有办法对NameValueCollection中的单个值轻松做到这一点?

我现在有这个,但似乎有点冗长:

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

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

3 个答案:

答案 0 :(得分:0)

我不确定您能得到多短。

一种可能是将Get放在创建KeyValuePair的位置

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

这应该适合您的情况。我将更进一步,将其分为两种方法-一种用于您的特定情况,另一种用于通用助手。

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

答案 1 :(得分:0)

如果将HttpRequestHeader.IfMatch.ToString()放入temp变量,然后内联temp etagValue,则不会那么冗长:

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

答案 2 :(得分:0)

如果是我,我将定义一个扩展方法,例如:

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

然后,您可以像这样编写原始代码:

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