有没有一种快速而简单的方法来检查一个键是否存在于NameValueCollection中,而不是遍历它?
寻找类似于Dictionary.ContainsKey()或类似的东西。
当然,有很多方法可以解决这个问题。只是想知道有没有人能帮我挠挠我的脑部。
发布于 2012-03-26 16:48:56
使用此方法:
private static bool ContainsKey(this NameValueCollection collection, string key)
{
if (collection.Get(key) == null)
{
return collection.AllKeys.Contains(key);
}
return true;
}
发布于 2012-03-26 16:21:22
可以,您可以使用Linq检查AllKeys
属性:
using System.Linq;
...
collection.AllKeys.Contains(key);
然而,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))
{
...
}
发布于 2014-01-26 01:08:56
我不认为这些答案中的任何一个都是非常正确/最优的。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);
}
https://stackoverflow.com/questions/9868726
复制相似问题