none
how to handle when Dictionary element does not exist RRS feed

  • Question

  • I made a class which is inherited from dictionary like following.

    public class MessageListDict : Dictionary<string, List<Message>>
        {
            //Add new elemet if key exists already or update existing element if key does not exist
            //returns
            //bool
            //   true  : Add or update succeeded
            //   false : some error occurred
            public bool AddNewMessage(string key, Message message)
            {
                bool ret = true;
                List<Message> messagelist;
                try
                {
                    if (this.ContainsKey(key))
                    {
                        messagelist = (List<Message>)this[key];
                    }
                    else
                    {
                        messagelist = new List<Message>();
                    }
                    messagelist.Add(message);
                    this.Add(key, messagelist);
                }
                catch
                {
                    ret = false;
                }
                return (ret);
            }
            public bool IsExistKey(string key)
            {
                bool ret = true;
                try
                {
                    if (!this.ContainsKey(key))
                    {
                        ret = false;
                    }
                }
                catch
                {
                    ret = false;
                }
                return (ret);
            }
            //Removes message list from the Dictionary
            //returns
            //bool
            //   true  : key exists and removed element successfully
            //   false : key doesn't exist 
            public bool RemoveMessageList(string key)
            {
                bool ret = true;
    
                if (this.ContainsKey(key))
                {
                    this.Remove(key);
                }
                else
                {
                    ret = false;
                }
                return (ret);
            }
            //Remove all elements from the Dictionary
            public void RemoveAllMessageLists()
            {
                this.Clear();
            }
    
            //Get messagelist
            //returns
            //List<Message> 
            //   not null  : if key exists, return message list
            //   null      : if key does not exist, return null
            public List<Message> GetMessageList(string key)
            {
                List<Message> messagelist = null;
                if (this.ContainsKey(key))
                {
                    messagelist = this[key];
                }
                return (messagelist);
            }
    
            //Get message
            //returns
            //string 
            //   not null string : if key exists, return message
            //   null string     : if key does not exist, return null string
            public string GetMessage(string key, string sid)
            {
                List<Message> messagelist;
                if (this.ContainsKey(key))
                {
                    messagelist = this[key];
                }
                else
                {
                    return("");
                }
    
                Message message = messagelist.Find(delegate(Message m)
                {
                    return m.SID == sid;
                });
                return (message.MessageBody);
            }
        }

    The Message class is like the followings.

    public class Message
        {
            private short m_direction;
            private DateTime m_message_datetime;
            private string m_message_body;
            private string m_firstname;
            private string m_sid;
            private string m_phoneno;
            public Message(string sid, short direction, DateTime message_datetime, string message_body, string firstname, string phoneno)
            {
                m_sid = sid;
                m_direction = direction;
                m_message_datetime = message_datetime;
                m_message_body = message_body;
                m_firstname = firstname;
                m_phoneno = phoneno;
            }
            public string SID
            {
                get { return m_sid; }
                set
                {
                    m_sid = value;
                }
            }
            public string MessageBody
            {
                get { return m_message_body; }
                set
                {
                    m_message_body = value;
                }
            }
            public DateTime MessageDateTime
            {
                get { return m_message_datetime; }
                set
                {
                    m_message_datetime = value;
                }
            }
            public Int16 Direction
            {
                get { return m_direction; }
                set
                {
                    m_direction = value;
                }
            }
            public string FirstName
            {
                get { return m_firstname; }
                set
                {
                    m_firstname = value;
                }
            }
            public string PhoneNo
            {
                get { return m_phoneno; }
                set
                {
                    m_phoneno = value;
                }
            }
        }

    From the client, I consume this class like following.

    MessageListDict messagelistdict = new MessageListDict();
    .
    .
    .
    .
    List<Message> messagelist;
    .
    .
    .
    messagelist = messagelistdict.GetMessageList(key);
    

    The error occurs in MessageListDict.GetMessageList(string key)'s last line, that is, return messagelist when key does not exist in the dictionary.

    How could I handle when dictionary key doesn't exist and return null?

    Saturday, January 11, 2020 5:35 AM

All replies

  • That's exactly what your code does.  Your sample code compiles and works fine for me.  EXACTLY what error message do you get?

    Tim Roberts | Driver MVP Emeritus | Providenza &amp; Boekelheide, Inc.

    Sunday, January 12, 2020 6:43 AM
  • Hi Jeff0803,
    >> //null: if key does not exist, return null
    Based on your code comments, if key does not exist and it will return null. I test your code and it is successful.
    So what is your requirement? And what "How could I handle when dictionary key doesn't exist and return null?" means?
    Please explain it in detail.
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, January 13, 2020 6:57 AM