返回基于int的字符串

时间:2013-04-18 09:09:45

标签: c# asp.net

有没有更容易的方法根据C#.NET2中int的值返回一个字符串,请问这个?

        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";
        }

5 个答案:

答案 0 :(得分:7)

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;

或使用三元运算符,但我发现它不太可读:

_relatedCategoryWidth = dictionary.ContainsKey(intRelatedItems) ? dictionary[intRelatedItems] : defaultValue;

或使用TryGetValue方法,正如CodesInChaos所建议:

if(!dictionary.TryGetValue(intRelatedItems, out _relatedCategoryWidth))
    _relatedCategoryWidth = defaultValue;

答案 1 :(得分:1)

好吧,既然你只对特殊套管连续的小整数感兴趣,你可以通过数组查找来做到这一点:

var values = new[] { "0", "12", "6", "4", "3" };
if (intRelatedItems >= 0 && intRelatedItems < values.Length)
{
    return values[intRelatedItems];
}
else
{
    return "0";
}

否则,最好的选择是使用普通的switch / case,并可能将其隐藏在方法中,以免混淆代码。

答案 2 :(得分:1)

您可以使用条件运算符:

_relatedCategoryWidth =
  intRelatedItems == 4 ? "3" :
  intRelatedItems == 3 ? "4" :
  intRelatedItems == 2 ? "6" :
  intRelatedItems == 1 ? "12" :
  "0";

这种写作方式强调一切都归结为对_relatedCategoryWidth变量的赋值。

答案 3 :(得分:0)

您可以使用int[]Dictionary<int, string>,具体取决于您的密钥。

例如:

int[] values = new int[] {100, 20, 10, 5};
return values[intRelatedItems];

显然只有当intRelatedItems只能取0到值的值时才有效。长度为-1。

如果不是这种情况,您可以使用“词典”。如果找不到密钥,这两种解决方案都会抛出异常。

答案 4 :(得分:0)

Dictionary<int, string> dictLookUp = new Dictionary<int, string>();
dictLookUp.Add(4, "3");
dictLookUp.Add(3, "4"};
dictLookUp.Add(2, "6"};
dictLookUp.Add(1, "12"};

int defaultVal = 0;

if (dictLookUp.ContainsKey(intRelatedItems))
{
    relatedCategoryWidth  = dictLookUp[intRelatedItems];
}
else
{ 
    intRelatedItems = defaultVal;
}