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?
LINQ approach :
Add the reference:
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...
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:
You may be interested in the generic
Range
type which is part of MiscUtil. It allows for iteration in a simple way as well:(Obviously that's also using some DateTime/TimeSpan-related extension methods, but you get the idea.)
Try something like:
In Pascal (Delphi) you have the following statement:
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.
Extension methods?
You can also do this awful hack:
Awful hack, improved:
Or, better yet (this does not allow duplicate lower bounds):