首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >检查NameValueCollection中是否存在密钥

检查NameValueCollection中是否存在密钥
EN

Stack Overflow用户
提问于 2012-03-26 16:18:05
回答 11查看 112.1K关注 0票数 156

有没有一种快速而简单的方法来检查一个键是否存在于NameValueCollection中,而不是遍历它?

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

当然,有很多方法可以解决这个问题。只是想知道有没有人能帮我挠挠我的脑部。

EN

回答 11

Stack Overflow用户

发布于 2012-03-26 16:48:56

使用此方法:

代码语言:javascript
复制
private static bool ContainsKey(this NameValueCollection collection, string key)
{
    if (collection.Get(key) == null)
    {
        return collection.AllKeys.Contains(key);
    }

    return true;
}
票数 60
EN

Stack Overflow用户

发布于 2012-03-26 16:21:22

可以,您可以使用Linq检查AllKeys属性:

代码语言:javascript
复制
using System.Linq;
...
collection.AllKeys.Contains(key);

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

代码语言:javascript
复制
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))
{
   ...
}
票数 16
EN

Stack Overflow用户

发布于 2014-01-26 01:08:56

我不认为这些答案中的任何一个都是非常正确/最优的。NameValueCollection不仅不区分空值和缺失值,而且它的键也不区分大小写。因此,我认为一个完整的解决方案应该是:

代码语言:javascript
复制
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);
}
票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9868726

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档