-4

The basic idea we follow is

if (i > 0 && i < 100) {

} else if (i > 100 && 1 < 150) {

}

This is the basic idea for range check..

Is there any good way to check these type of conditions.

Thanks in advance for the help!

tremendows
  • 4,262
  • 3
  • 34
  • 51

3 Answers3

1

int endX=200;

Click on below link you will get what is the difference @Steve

var switchCond = new Dictionary<Func<int, bool>, Action>
               {
                 { x => x <= 290 , () => endX=244  },  
                 { x => x <= 530, () => endX=488 },
                 { x => x <= 790 , () => endX=732 },
                 { x => x <=1000 || x > 976 , () => endX=976 }

                };
                switchCond.First(sw => sw.Key(endX)).Value();

[Switch case: can I use a range instead of a one number

Community
  • 1
  • 1
0

use ternary operator

 var range = 
     i < 100? "Range1":
     i < 150? "Range2":
     i < 200? "Range3":
     i < 250? "Range4":
     i < 300? "Range5": 
              "Range6";

This is example only to show technique. obviously, you must adapt it to your code objectives and appropriate range definitions. (by the way, in your example, using if- else if, your code misses the value 100. you need to decide which range 100 should be included in, and change one of the inequality operators to either <= or >=.

Charles Bretana
  • 143,358
  • 22
  • 150
  • 216
0

you could have switch construct "handle" ranges by use of a List of your bounds:

        List<int> bounds = new List<int>() {int.MinValue, 0, 100, 150, 200, 300, int.MaxValue };

        switch (bounds.IndexOf(bounds.Last(x => x < j)))
        {
            case 0: // <=0
                break;

            case 1: // > 0 and <=100
                break;
            case 2: // > 100 and <= 150
                break;
            case 3: // > 150 and <=200
                break;
            case 4: // > 200 and <=300
                break;

            case 5: // >300
                break;
        }

where you may have to add some additional checks to

user3598756
  • 28,893
  • 4
  • 18
  • 28