Determine if a number falls within a specified set of ranges

后端 未结 8 1543
耶瑟儿~
耶瑟儿~ 2021-02-02 13:45

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         


        
8条回答
  •  渐次进展
    2021-02-02 14:02

    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.)

提交回复
热议问题