Check if Key Exists in NameValueCollection

后端 未结 12 742
执念已碎
执念已碎 2020-12-13 16:42

Is there a quick and simple way to check if a key exists in a NameValueCollection without looping through it?

Looking for something like Dictionary.ContainsKey() or

12条回答
  •  我在风中等你
    2020-12-13 17:25

    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:

    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().Contains(key, StringComparer.OrdinalIgnoreCase);
    }
    

提交回复
热议问题