mercredi 5 juillet 2017

Efficient alternative way than using multiple if statements to check keys in a dictionary

I have around 45 if statements that checks the dictionary to see if it has that key.

    private List<MessageName> createMsgObject(Dictionary<string, string> infoHash, Dictionary<string, Int16> msgDescritionAndID)
    {
            MessageName msgName = null;
            List<MessageName> msgNameList = new List<MessageName>();
            var msgObjOuter = new MessageName();

            if (infoHash.ContainsKey("redis_version"))
            {
                msgName = new MessageName();
                msgName.MessageID = msgDescritionAndID["redis_version"];
                msgName.DiagnosticCnt = 0;
                msgName.DiagnosticStr = infoHash["redis_version"]; 
                msgNameList.Add(msgName);
            }
           if (infoHash.ContainsKey("uptime_in_seconds"))
           {
            msgName = new MessageName();
            msgName.MessageID = msgDescritionAndID["uptime_in_seconds"];
            msgName.DiagnosticCnt = Convert.ToInt32(infoHash["uptime_in_seconds"]);
            msgName.DiagnosticStr = "";
            msgNameList.Add(msgName);
          }
          //... 40 more if statements
         return msgNameList;
   }

This really hasn't had a hit on performance but I was wondering if there was a more efficient way to check all the keys in that dictionary and if it does insert it's property in to a MessageName object and insert that object into a list. I don't know if switch statements would help in performance.

Aucun commentaire:

Enregistrer un commentaire