C# 检查 NameValueCollection 中是否存在 Key
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9868726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if Key Exists in NameValueCollection
提问by Muhammad Yussuf
Is there a quick and simple way to check if a key exists in a NameValueCollection without looping through it?
有没有一种快速而简单的方法来检查 NameValueCollection 中是否存在一个键而无需遍历它?
Looking for something like Dictionary.ContainsKey() or similar.
寻找类似 Dictionary.ContainsKey() 或类似的东西。
There are many ways to solve this of course. Just wondering if someone can help scratch my brain itch.
当然有很多方法可以解决这个问题。只是想知道是否有人可以帮助我挠痒痒。
采纳答案by abatishchev
From MSDN:
从MSDN:
This property returns null in the following cases:
1) if the specified key is not found;
此属性在以下情况下返回 null:
1) 如果没有找到指定的键;
So you can just:
所以你可以:
NameValueCollection collection = ...
string value = collection[key];
if (value == null) // key doesn't exist
2) if the specified key is found and its associated value is null.
2) 如果找到指定的键并且其关联值为空。
collection[key]calls base.Get()then base.FindEntry()which internally uses Hashtablewith performance O(1).
collection[key]base.Get()然后调用base.FindEntry()内部使用Hashtable的性能 O(1)。
回答by Rich O'Kelly
Yes, you can use Linq to check the AllKeysproperty:
是的,您可以使用 Linq 来检查AllKeys属性:
using System.Linq;
...
collection.AllKeys.Contains(key);
However a Dictionary<string, string[]>would be far more suited to this purpose, perhaps created via an extension method:
然而, aDictionary<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))
{
...
}
回答by Codrin Eugeniu
回答by Kirill Polishchuk
Use this method:
使用这个方法:
private static bool ContainsKey(this NameValueCollection collection, string key)
{
if (collection.Get(key) == null)
{
return collection.AllKeys.Contains(key);
}
return true;
}
It is the most efficient for NameValueCollectionand doesn't depend on does collection contain nullvalues or not.
它是最有效的,NameValueCollection并且不依赖于集合是否包含null值。
回答by Jaguar
If the collection size is small you could go with the solution provided by rich.okelly. However, a large collection means that the generation of the dictionary may be noticeably slower than just searching the keys collection.
如果集合很小,您可以使用rich.okelly 提供的解决方案。但是,大型集合意味着字典的生成可能比仅搜索键集合要慢得多。
Also, if your usage scenario is searching for keys in different points in time, where the NameValueCollection may have been modified, generating the dictionary each time may, again, be slower than just searching the keys collection.
此外,如果您的使用场景是在不同的时间点搜索键,其中 NameValueCollection 可能已被修改,则每次生成字典可能再次比仅搜索键集合慢。
回答by ChaseMedallion
I don't think any of these answers are quite right/optimal. NameValueCollection not only doesn't distinguish between null values and missing values, it's also case-insensitive with regards to it's keys. Thus, I think a full solution would be:
我认为这些答案中的任何一个都不完全正确/最佳。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);
}
回答by codys-hole
This could also be a solution without having to introduce a new method:
这也可以是一种无需引入新方法的解决方案:
item = collection["item"] != null ? collection["item"].ToString() : null;
回答by Stefan Steiger
As you can see in the reference sources, NameValueCollectioninherits from NameObjectCollectionBase.
正如您在参考源中看到的,NameValueCollection继承自NameObjectCollectionBase。
So you take the base-type, get the private hashtable via reflection, and check if it contains a specific key.
因此,您采用基本类型,通过反射获取私有哈希表,并检查它是否包含特定键。
For it to work in Mono as well, you need to see what the name of the hashtable is in mono, which is something you can see here(m_ItemsContainer), and get the mono-field, if the initial FieldInfo is null (mono-runtime).
为了让它也能在 Mono 中工作,您需要查看单声道中哈希表的名称是什么,这是您可以在此处看到的内容(m_ItemsContainer),如果初始 FieldInfo 为空(单声道-运行)。
Like this
像这样
public static class ParameterExtensions
{
private static System.Reflection.FieldInfo InitFieldInfo()
{
System.Type t = typeof(System.Collections.Specialized.NameObjectCollectionBase);
System.Reflection.FieldInfo fi = t.GetField("_entriesTable", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if(fi == null) // Mono
fi = t.GetField("m_ItemsContainer", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
return fi;
}
private static System.Reflection.FieldInfo m_fi = InitFieldInfo();
public static bool Contains(this System.Collections.Specialized.NameValueCollection nvc, string key)
{
//System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection();
//nvc.Add("hello", "world");
//nvc.Add("test", "case");
// The Hashtable is case-INsensitive
System.Collections.Hashtable ent = (System.Collections.Hashtable)m_fi.GetValue(nvc);
return ent.ContainsKey(key);
}
}
for ultra-pure non-reflective .NET 2.0 code, you can loop over the keys, instead of using the hash-table, but that is slow.
对于超纯非反射 .NET 2.0 代码,您可以遍历键,而不是使用哈希表,但这很慢。
private static bool ContainsKey(System.Collections.Specialized.NameValueCollection nvc, string key)
{
foreach (string str in nvc.AllKeys)
{
if (System.StringComparer.InvariantCultureIgnoreCase.Equals(str, key))
return true;
}
return false;
}
回答by CodeShouldBeEasy
In VB it's:
在VB中它是:
if not MyNameValueCollection(Key) is Nothing then
.......
end if
In C# should just be:
在 C# 中应该只是:
if (MyNameValueCollection(Key) != null) { }
Not sure if it should be nullor ""but this should help.
不确定它是否应该null或""但这应该有所帮助。

