Determine if a number falls within a specified set

2019-03-11 05:37发布

I'm looking for a fluent way of determining if a number falls within a specified set of ranges. My current code looks something like this:

int x = 500; // Could be any number

if ( ( x > 4199 && x < 6800 ) ||
     ( x > 6999 && x < 8200 ) ||
     ( x > 9999 && x < 10100 ) ||
     ( x > 10999 && x < 11100 ) ||
     ( x > 11999 && x < 12100 ) )
{
    // More awesome code
}

Is there a better way of doing this?

标签: c# range
8条回答
\"骚年 ilove
2楼-- · 2019-03-11 06:05

LINQ approach :

Add the reference:

using System.Linq;

        /// <summary>
        /// Test to see if value is in specified range.
        /// </summary>
        /// <param name="aStart">int</param>
        /// <param name="aEnd">int</param>
        /// <param name="aValueToTest">int</param>
        /// <returns>bool</returns>
        public static bool CheckValueInRange(int aStart, int aEnd, int aValueToTest)
        {
            // check value in range...
            bool ValueInRange = Enumerable.Range(aStart, aEnd).Contains(aValueToTest);
            // return value...
            return ValueInRange;
        }
查看更多
Evening l夕情丶
3楼-- · 2019-03-11 06:16

I personally prefer the extension method suggested by @Anton - but if you can't do that, and are going to stick with your current code, I think you could make it more readable by reversing the first set of conditions on each line as follows...

int x = 500; // Could be any number
if ( ( 4199 < x && x < 6800 ) ||
     ( 6999 < x && x < 8200 ) ||
     ( 9999 < x && x < 10100 ) ||
     ( 10999 < x && x < 11100 ) ||
     ( 11999 < x && x < 12100 ) )
{
    // More awesome code
}
查看更多
何必那么认真
4楼-- · 2019-03-11 06:17

Define a Range type, then create a set of ranges and an extension method to see whether a value lies in any of the ranges. Then instead of hard-coding the values, you can create a collection of ranges and perhaps some individual ranges, giving them useful names to explain why you're interested in them:

static readonly Range InvalidUser = new Range(100, 200);
static readonly Range MilkTooHot = new Range (300, 400);

static readonly IEnumerable<Range> Errors =
    new List<Range> { InvalidUser, MilkTooHot };

...

// Normal LINQ (where Range defines a Contains method)
if (Errors.Any(range => range.Contains(statusCode))
// or (extension method on int)
if (statusCode.InAny(Errors))
// or (extension methods on IEnumerable<Range>)
if (Errors.Any(statusCode))

You may be interested in the generic Range type which is part of MiscUtil. It allows for iteration in a simple way as well:

foreach (DateTime date in 19.June(1976).To(25.December(2005)).Step(1.Days()))
{
    // etc
}

(Obviously that's also using some DateTime/TimeSpan-related extension methods, but you get the idea.)

查看更多
对你真心纯属浪费
5楼-- · 2019-03-11 06:17

Try something like:

struct Range
{
   public readonly int LowerBound;
   public readonly int UpperBound; 

   public Range( int lower, int upper )
   { LowerBound = lower; UpperBound = upper; }

   public bool IsBetween( int value )
   { return value >= LowerBound && value <= UpperBound; }
}

public void YourMethod( int someValue )
{
   List<Range> ranges = {new Range(4199,6800),new Range(6999,8200),
                         new Range(9999,10100),new Range(10999,11100),
                         new Range(11999,12100)};

   if( ranges.Any( x => x.IsBetween( someValue ) )
   {
      // your awesome code...
   }
}
查看更多
一纸荒年 Trace。
6楼-- · 2019-03-11 06:17

In Pascal (Delphi) you have the following statement:

if x in [40..80] then
begin
end

So if a value x falls in that range you execute your command. I was looking for the C# equivalent to this but can't find something as simple and 'elegant' as this.

This if in() then statement accepts strings, bytes, etc.

查看更多
不美不萌又怎样
7楼-- · 2019-03-11 06:20

Extension methods?

bool Between(this int value, int left, int right)
{ 
   return value > left && value < right; 
}

if(x.Between(4199, 6800) || x.Between(6999, 8200) || ...)

You can also do this awful hack:

bool Between(this int value, params int[] values)
{
    // Should be even number of items
    Debug.Assert(values.Length % 2 == 0); 

    for(int i = 0; i < values.Length; i += 2)
        if(!value.Between(values[i], values[i + 1])
            return false;

    return true;
}

if(x.Between(4199, 6800, 6999, 8200, ...)

Awful hack, improved:

class Range
{
    int Left { get; set; }
    int Right { get; set; }

    // Constructors, etc.
}

Range R(int left, int right)
{
    return new Range(left, right)
}

bool Between(this int value, params Range[] ranges)
{
    for(int i = 0; i < ranges.Length; ++i)
        if(value > ranges[i].Left && value < ranges[i].Right)
            return true;

    return false;
}

if(x.Between(R(4199, 6800), R(6999, 8200), ...))

Or, better yet (this does not allow duplicate lower bounds):

bool Between(this int value, Dictionary<int, int> ranges)
{
    // Basically iterate over Key-Value pairs and check if value falls within that range
}

if(x.Between({ { 4199, 6800 }, { 6999, 8200 }, ... }
查看更多
登录 后发表回答