Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

My code has a IF condition where I am checking if a particular value falls between a set of integers (like 26,34,58,112 etc). I have written them through a OR operator (||) however it becomes a long statement to view.

The example of the code can be this way..

If (StatusOfCondition = "26") || (StatusOfCondition = "28") || (StatusOfCondition = "34") etc etc

Is there any other way through which I can write a loop and make it shorter?

Any help is appreciated.
Posted
Comments
ccalma 21-Apr-14 3:29am    
What is the source of the set of integers? You can create a list of integers, then use Contains method to check if the value exists in the list.

There are quite a lot of ways you can do that: particularly if you set up an array or list of "allowed values" - which can be a static readonly list.

The first is to use a switch instead:
C#
string StatusOfCondition = "26";
switch (StatusOfCondition)
    {
    case "26":
    case "28":
    case "34":
        // Do something
        break;
    default:
        // Do something for non matching values
        break;
    }
The framework can optimise switches pretty well.
The array version may be better though:
C#
private static readonly string[] allowedValues = new string[] { "26", "28", "34" };

    ...
    string StatusOfCondition = "26";
    if (allowedValues.Contains(StatusOfCondition))
        {
        ...
        }
 
Share this answer
 
Comments
DamithSL 21-Apr-14 3:33am    
switch again will be lengthy option but my 5 for the array solution
OriginalGriff 21-Apr-14 3:46am    
It's fairly long to write - but it is clear and obvious: you don't need to look elsewhere to check what values are allowed. And .NET can optimise it to a faster check than the array method.
Emre Ataseven 21-Apr-14 10:51am    
5 for switch case. Provides readability and lower complexity. Average case complexity of array search O(logn) while switch jump O(1), if speed matters. And what if you decide to do different things if value is in set {56,78,56}, create another array? Switch-case rocks! :)
C#
// create list of integers with all options like below  
var list = new List<int> {26,34,58,112};
var StatusOfCondition = 58; // for testing..
//you can simple use Contains method like below 
if(list.Contains(StatusOfCondition))
{
  // do something 
}
 
Share this answer
 
v3
Comments
gpthakur 23-Apr-14 3:00am    
Hi, this solution seems to work. I am doing a round of testing to be sure this is the final way to go. Thanks a lot for your help

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900