How can I detect if this dictionary key exists in C#?

后端 未结 5 441
青春惊慌失措
青春惊慌失措 2020-11-30 17:51

I am working with the Exchange Web Services Managed API, with contact data. I have the following code, which is functional, but not ideal:

foreach (         


        
5条回答
  •  再見小時候
    2020-11-30 18:17

    Here is a little something I cooked up today. Seems to work for me. Basically you override the Add method in your base namespace to do a check and then call the base's Add method in order to actually add it. Hope this works for you

    using System;
    using System.Collections.Generic;
    using System.Collections;
    
    namespace Main
    {
        internal partial class Dictionary : System.Collections.Generic.Dictionary
        {
            internal new virtual void Add(TKey key, TValue value)
            {   
                if (!base.ContainsKey(key))
                {
                    base.Add(key, value);
                }
            }
        }
    
        internal partial class List : System.Collections.Generic.List
        {
            internal new virtual void Add(T item)
            {
                if (!base.Contains(item))
                {
                    base.Add(item);
                }
            }
        }
    
        public class Program
        {
            public static void Main()
            {
                Dictionary dic = new Dictionary();
                dic.Add(1,"b");
                dic.Add(1,"a");
                dic.Add(2,"c");
                dic.Add(1, "b");
                dic.Add(1, "a");
                dic.Add(2, "c");
    
                string val = "";
                dic.TryGetValue(1, out val);
    
                Console.WriteLine(val);
                Console.WriteLine(dic.Count.ToString());
    
    
                List lst = new List();
                lst.Add("b");
                lst.Add("a");
                lst.Add("c");
                lst.Add("b");
                lst.Add("a");
                lst.Add("c");
    
                Console.WriteLine(lst[2]);
                Console.WriteLine(lst.Count.ToString());
            }
        }
    }
    

提交回复
热议问题