检查NameValueCollection中是否存在密钥

Muh*_*suf 133 .net c# namevaluecollection

是否有一种快速而简单的方法来检查NameValueCollection中是否存在密钥而不通过它进行循环?

寻找像Dictionary.ContainsKey()或类似的东西.

当然,有很多方法可以解决这个问题.只是想知道是否有人可以帮助划伤我的大脑痒.

aba*_*hev 170

来自MSDN:

在以下情况下,此属性返回null:

1)如果未找到指定的密钥;

所以你可以:

NameValueCollection collection = ...
string value = collection[key];
if (value == null) // key doesn't exist
Run Code Online (Sandbox Code Playgroud)

2)如果找到指定的密钥且其关联值为空.

collection[key]base.Get()然后调用base.FindEntry()内部使用Hashtable性能O(1).

  • 在以下情况下,此属性返回null:1)如果未找到指定的键; 2)如果找到指定的键并且其关联值为null.此属性不区分这两种情况. (35认同)
  • 对@abatishchev,然而OP说"检查密钥是否存在".以null为关键不存在是不正确的.最后没有妥协没有答案(没有循环,使用空字符串) (13认同)
  • 如果你真的想在你的集合中存储`null`,那将无法工作...... (10认同)

Kir*_*huk 50

使用此方法:

private static bool ContainsKey(this NameValueCollection collection, string key)
{
    if (collection.Get(key) == null)
    {
        return collection.AllKeys.Contains(key);
    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)

它是最有效的,NameValueCollection并且不依赖于集合是否包含null值.

  • 使用此解决方案时,请记住`使用System.Linq;`. (5认同)

Cha*_*ion 14

我不认为这些答案中的任何一个都是正确/最佳的.NameValueCollection不仅不区分空值和缺失值,它对于它的键也不区分大小写.因此,我认为一个完整的解决方案是:

public static bool ContainsKey(this NameValueCollection @this, string key)
{
    return @this.Get(key) != null 
        // I'm using Keys instead of AllKeys because AllKeys, being a mutable array,
        // can get out-of-sync if mutated (it weirdly re-syncs when you modify the collection).
        // I'm also not 100% sure that OrdinalIgnoreCase is the right comparer to use here.
        // The MSDN docs only say that the "default" case-insensitive comparer is used
        // but it could be current culture or invariant culture
        || @this.Keys.Cast<string>().Contains(key, StringComparer.OrdinalIgnoreCase);
}
Run Code Online (Sandbox Code Playgroud)


Ric*_*lly 12

是的,您可以使用Linq来检查AllKeys房产:

using System.Linq;
...
collection.AllKeys.Contains(key);
Run Code Online (Sandbox Code Playgroud)

然而,a Dictionary<string, string[]>更适合这个目的,可能是通过扩展方法创建的:

public static void Dictionary<string, string[]> ToDictionary(this NameValueCollection collection) 
{
    return collection.Cast<string>().ToDictionary(key => key, key => collection.GetValues(key));
}

var dictionary = collection.ToDictionary();
if (dictionary.ContainsKey(key))
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

  • @abatishchev确实,`collection [key]`不区分不存在的键和存储该键的空值. (4认同)