Check if Key Exists in NameValueCollection

后端 未结 12 704
执念已碎
执念已碎 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:05

    As you can see in the reference sources, NameValueCollection inherits from 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).

    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.

    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;
    }
    
    0 讨论(0)
  • 2020-12-13 17:05

    I am using this collection, when I worked in small elements collection.

    Where elements lot, I think need use "Dictionary". My code:

    NameValueCollection ProdIdes;
    string prodId = _cfg.ProdIdes[key];
    if (string.IsNullOrEmpty(prodId))
    {
        ......
    }
    

    Or may be use this:

     string prodId = _cfg.ProdIdes[key] !=null ? "found" : "not found";
    
    0 讨论(0)
  • 2020-12-13 17:07

    Yes, you can use Linq to check the AllKeys property:

    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:

    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))
    {
       ...
    }
    
    0 讨论(0)
  • This could also be a solution without having to introduce a new method:

        item = collection["item"] != null ? collection["item"].ToString() : null;
    
    0 讨论(0)
  • 2020-12-13 17:08

    You could use the Get method and check for null as the method will return null if the NameValueCollection does not contain the specified key.

    See MSDN.

    0 讨论(0)
  • 2020-12-13 17:09

    In VB it's:

    if not MyNameValueCollection(Key) is Nothing then
    .......
    end if
    

    In C# should just be:

    if (MyNameValueCollection(Key) != null) { }
    

    Not sure if it should be null or "" but this should help.

    0 讨论(0)
提交回复
热议问题