Check if a variable is in an ad-hoc list of values

后端 未结 7 1208

Is there a shorter way of writing something like this:

if(x==1 || x==2 || x==3) // do something

Wha

7条回答
  •  不思量自难忘°
    2020-12-08 18:49

    You can create a simple Dictionary that'll be used as a Decision Table for that problem:

            //Create your decision-table Dictionary
            Action actionToPerform1 = () => Console.WriteLine("The number is okay");
            Action actionToPerform2 = () => Console.WriteLine("The number is not okay");
            var decisionTable = new Dictionary
                {
                    {1, actionToPerform1},
                    {2, actionToPerform1},
                    {3, actionToPerform1},
                    {4, actionToPerform2},
                    {5, actionToPerform2},
                    {6, actionToPerform2}
                };
    
            //According to the given number, the right *Action* will be called.
            int theNumberToTest = 3;
            decisionTable[theNumberToTest](); //actionToPerform1 will be called in that case.
    

    Once you've initialized your Dictionary, all left to do is:

    decisionTable[theNumberToTest]();

提交回复
热议问题