从整数列表切换大小写,代码优化

本文关键字:大小写 代码优化 整数 列表 | 更新日期: 2023-09-27 18:27:33

我有一个大的开关案例,我还有一个整数列表,比如{16106168331610747905161087897716108789777111010049}我想做以下

int a;
    switch (incomingint)
    {
    case 1:
    //some code
    break;
    case 2:
    //some code
    breakl
    //now i want to check if this one is one of the list's integers or not
    //so i did the following
    case 1610616833:
    a=0;
    break;
    case 1610747905:
    a=1;
    break;
    case 1610878977:
    a=2;
    break;
    }

问题是:

  1. 我在列表中有大约16个元素
  2. 对于列表的一个成员,代码几乎相同,除了我为设置的值。注意:只有当传入对象是列表成员之一时,才会设置"a"的值那么,与其编写所有的代码,还有什么方法可以优化这些代码吗

从整数列表切换大小写,代码优化

您可以使用字典进行此转换:

Dictionary<int, int> transformation = new Dictionary<int, int>
{
   { 1000, 0 },
   { 1001, 1 },
// etc
};
int a = 0; // Default value
if (transformation.TryGetValue(incomingint, out a))
{
   // a has the value. If you need to do something else, you might do it here because you know that dictionary had incomingint
}

您可以创建一个字典,该字典将是您的列表项和a的值之间的映射。

var dict = new Dictionary<int,int>();
dict.Add(1000, 0);
dict.Add(1001, 1);
dict.Add(1002, 5);
...

后来:

a = dict[incomingint];

如果有直接的方法从incomingint计算a,只需在计算中使用incomingint。你发布的数据看起来很简单:

a = incomingint - 1000;

对于值为1000及以上的incomingint

似乎可以通过编写来优化这一点

if (incomingint > 1000) a = incomingint - 1000;

在其他新闻中,如果你的列表中有16个int,你几乎肯定不需要优化它。这是一个非常小、非常快的工作量。