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).
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值.
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)
| 归档时间: |
|
| 查看次数: |
94178 次 |
| 最近记录: |