Sara S.
Sara S.

Reputation: 1375

switch case from a list of integers ,code optimization

i have a large switch case ,and i also have a list of integers say{1610616833,1610747905,1610878977,1610878977,1611010049} i want to do the following

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

The problem is :

  1. I have around 16 element in the list
  2. The code in the case of one of the list's members is almost the same except in the value i set for a . NOTE: setting the value of 'a' occurs only when the incomingint is one of the list members so instead of writing all of that code, is there any way to optimize this code??

Upvotes: 0

Views: 1020

Answers (3)

Nikola Markovinović
Nikola Markovinović

Reputation: 19356

You could use a dictionary for this transformation:

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
}

Upvotes: 3

Oded
Oded

Reputation: 499132

You can create a dictionary that will be a mapping between your list items and values of a.

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

And later:

a = dict[incomingint];

If there is a direct way to compute a from incomingint, just use incomingint in the calculation. The data you posted looks like you could simply do:

a = incomingint - 1000;

For incomingint of values 1000 and above.

Upvotes: 2

Alexander Corwin
Alexander Corwin

Reputation: 1167

it seems like you can optimize this by writing

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

in other news, if you have 16 ints in a list, you almost definitely don't need to optimize it. that's a tiny, blazing-fast amount of work.

Upvotes: 1

Related Questions