Specifying Ranges in C#

后端 未结 3 1070
遇见更好的自我
遇见更好的自我 2021-01-23 02:46

I have 6 Ranges:

1000000-5000000
50000001-10000000
10000001-25000000
25000001-50000000
50000001-75000000
75000001-100000000

Now how do I say th

3条回答
  •  轮回少年
    2021-01-23 03:09

    If your ranges are continuous like in the examples you gave, then please note that you do not need any 'interval'.

    Continuous ranges like 1-9, 10-19, 20-29 actually define a "threshold points": 9|10, 19|20 and so on. Instead of checking a 1-9, 10-19, 20-29 ranges, you may simply:

    if ( x <= 9 )
       ...
    else if ( x <= 19 )
       ...
    else if ( x <= 29 )
       ...
    

    Note that the else part guarantees you the lower bound in each case.

    EDIT:

    You've updated your code with result = 10 and etc. If you really need only such simple operation, then you can define a list:

    var levelsAndValues = List>();
    levelsAndValues.Add(Tuple.Create(5000000, 10));
    levelsAndValues.Add(Tuple.Create(10000000, 20));
    ...
    

    and run a simple loop over it:

    int limit = 1000000;
    int result = 0;
    foreach(var level in levelsAndValues)
        if(limit > level.Item1)
            result = level.Item2;
        else
            break;
    

    or linq-lookup:

    var result = levelsAndValues.Where(level => limit > level.Item1)
                                .Select(level => level.Item2)
                                .LastOrDefault();
    

    Now, if your ranges are noncontiguous - you just have to introduce third value to the tuple: {low,high,value} instead of just {high, value} like I wrote above, and then update the filtering accordingly. This might be a good time to also change the Tuple to a custom type.

    Or, to use the Interval datatype posted here, just like Marting hinted in the comments.

提交回复
热议问题