A "good practice" way to check for multiple conditions


I guess the title doesn’t say much but I’m looking for a way to check for multiple “greater than / less than” conditions.

Example: I’m querying a database and getting some records back as DT which I then filter.

Example of what I’d like to achieve:
If the number of filtered rows is 0 then do X
If the number is between 1 and 11 then do Y
If the number is exactly 11 then do Y and also do Z
If number of filtered rows is greater than 11 then throw exception

What would be the most “graceful” way to do it? I was thinking of first doing a couple ifs to check which case I’m in and then assign an int or string for each case and then do a switch.

In this example I’m a bit concerned about having too many ifs, though I could do an invoke code to have less activities, however I’m wondering if there’s a better way to handle it.

Also wondering if for the “If the number is exactly 11 then do Y and also do Z” I would need to do a separate case when rowcount=11 that does Y and Z or it’s possible to check for multiple overlapping cases (but then how would the robot know which case to handle first?). This case is not that important now, however it might possible in the future that I need to look for all cases where the number of rows is a multiplication of 11 - so for example if RowCount mod 11 equals 0

Any good practice ideas?


You can try to use a switch case or a flow switch, since you know the expected value.

Thanks, makes sense. I also found this nice code courtesy of Steve Gomez @ stackoverflow, should be good for invoking. Looks like I was very very late to the party not knowing this is possible in C# :stuck_out_tongue:

Original Answer for C# 7

A bit late to the game for this question, but in recent changes introduced in C# 7 (Available by default in Visual Studio 2017/.NET Framework 4.6.2), range-based switching is now possible with the switch statement.


int i = 63;

switch (i)
    case int n when (n >= 100):
        Console.WriteLine($"I am 100 or above: {n}");

    case int n when (n < 100 && n >= 50 ):
        Console.WriteLine($"I am between 99 and 50: {n}");

    case int n when (n < 50):
        Console.WriteLine($"I am less than 50: {n}");

original SO reference: c# - Switch case: can I use a range instead of a one number - Stack Overflow

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.