如何将 NameValueCollection 转换为 KeyValuePair

How can I convert a NameValueCollection to a KeyValuePair

我想转换一个NameValueCollection to a 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);
}

我不确定你能得到多短。

一种可能是将 Get 放在创建 KeyValuePair 的地方

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

这应该适合你的情况。我会更进一步,将它分成 2 种方法 - 一种用于您的特定情况,一种用于通用助手。

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

如果将 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));
}

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

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