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
Post a Comment