dimanche 13 août 2017

Avoidable if-else in C#

Here is a finished Roman to Decimal numeral convertor.

Dictionary<char,int> nTrans = new Dictionary<char,int>();
            nTrans.Add('I',1);
            nTrans.Add('V', 5);
            nTrans.Add('X', 10);
            nTrans.Add('L', 50);
            nTrans.Add('C', 100);
            nTrans.Add('D', 500);
            nTrans.Add('M', 1000);

            string rNum = "XV";
            int dNum = 0;

            for (int i = 0; i < rNum.Length; i++)
            {
                if (i < rNum.Length-1)
                {
                    if (nTrans[rNum[i]] < nTrans[rNum[i + 1]])
                    {
                        dNum -= nTrans[rNum[i]];
                    }
                    else
                    {
                        dNum += nTrans[rNum[i]];
                    }
                }
                else
                {
                    dNum += nTrans[rNum[i]];
                }
            }

But i can't figure out how to escape from using this if-else statement:

if (i < rNum.Length-1)
{
//Code
}
else
{
dNum += nTrans[rNum[i]];
}

Any suggestions how can i avoid using it. The question is not urgent it is only for optimizing and improving my coding skills! Will be thankful if you can give me a shoulder.

Aucun commentaire:

Enregistrer un commentaire