确定一个数字是否在一组指定的范围内

Determine if a number falls within a specified set of ranges(确定一个数字是否在一组指定的范围内)
本文介绍了确定一个数字是否在一组指定的范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种确定数字是否在指定范围内的流畅方法.我当前的代码如下所示:

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
}

有更好的方法吗?

推荐答案

扩展方法?

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

可怕的 hack,改进:

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 }, ... }

这篇关于确定一个数字是否在一组指定的范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)