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
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 Errors =
new List { 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)
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.)