c# - Return string based on int -


is there easier way return string based on value of int in c# .net2 this, please?

        if (intrelateditems == 4)         {             _relatedcategorywidth = "3";         }         else if (intrelateditems == 3)         {             _relatedcategorywidth = "4";         }         else if (intrelateditems == 2)         {             _relatedcategorywidth = "6";         }         else if (intrelateditems == 1)         {             _relatedcategorywidth = "12";         }         else         {             _relatedcategorywidth = "0";         } 

dictionary<int, string> dictionary = new dictionary<int, string> {     {4, "3"},     {3, "4"},     {2, "6"},     {1, "12"}, };  string defaultvalue = "0";  if(dictionary.containskey(intrelateditems))     _relatedcategorywidth = dictionary[intrelateditems]; else     _relatedcategorywidth = defaultvalue; 

or use ternary operator, find less readable:

_relatedcategorywidth = dictionary.containskey(intrelateditems) ? dictionary[intrelateditems] : defaultvalue; 

or use trygetvalue method, codesinchaos kindly suggested:

if(!dictionary.trygetvalue(intrelateditems, out _relatedcategorywidth))     _relatedcategorywidth = defaultvalue; 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -