How to elegantly check if a number is within a range?

There are a lot of options:

int x = 30;
if (Enumerable.Range(1,100).Contains(x))  //true

And indeed basic if more elegantly can be written with reversing order in the first check:

if (1 <= x && x <= 100)   //true

Also, check out this SO post for regex options.

Notes:

  • LINQ solution is strictly for style points – since Contains iterates over all items its complexity is O(range_size) and not O(1) normally expected from a range check.
    More generic version for other ranges (notice that second argument is count, not end):

    if (Enumerable.Range(start, end - start + 1).Contains(x)
    
  • There is temptation to write if solution without && like 1 <= x <= 100 – that look really elegant, but in C# leads to a syntax error “Operator ‘<=’ cannot be applied to operands of type ‘bool’ and ‘int'”

Leave a Comment