代码之家  ›  专栏  ›  技术社区  ›  DannyD

如何将NameValueCollection转换为KeyValuePair

  •  0
  • DannyD  · 技术社区  · 6 年前

    我想转换一个 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 回复  |  直到 6 年前
        1
  •  0
  •   pamcevoy    6 年前

    我不知道你能缩短多少。

    一种可能是将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));
    }
    
        2
  •  0
  •   Olivier Jacot-Descombes    6 年前

    如果你把 HttpRequestHeader.IfMatch.ToString() 输入一个临时变量,而不是内联临时变量 etagValue :

    private KeyValuePair<string, string> GetEtagHeader(NameValueCollection collection)
    {
        string key = HttpRequestHeader.IfMatch.ToString();
        return new KeyValuePair<string, string>(key, collection.Get(key));
    }
    
        3
  •  0
  •   John Wu    6 年前

    如果是我,我会像这样定义一个扩展方法:

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