C#中有“之间”功能吗?

时间:2011-02-16 22:58:54

标签: c#

谷歌不明白“之间”是我正在寻找的功能的名称,并且没有任何相关内容。

例如:我想在一次操作中检查5是否在0到10之间

17 个答案:

答案 0 :(得分:109)

目前尚不清楚“一个操作”是什么意思,但不是,我知道没有操作员/框架方法可以确定一个项目是否在一个范围内。

你当然可以自己写一个扩展方法。例如,这里假设两个端点上的间隔关闭

public static bool IsBetween<T>(this T item, T start, T end)
{
    return Comparer<T>.Default.Compare(item, start) >= 0
        && Comparer<T>.Default.Compare(item, end) <= 0;
}

然后将其用作:

bool b = 5.IsBetween(0, 10); // true

答案 1 :(得分:79)

不,但你可以写自己的:

public static bool Between(this int num, int lower, int upper, bool inclusive = false)
{
    return inclusive
        ? lower <= num && num <= upper
        : lower < num && num < upper;
}

答案 2 :(得分:29)

这是一个完整的课程。

/// <summary>
/// An extension class for the between operation
/// name pattern IsBetweenXX where X = I -> Inclusive, X = E -> Exclusive
/// <a href="https://stackoverflow.com/a/13470099/37055"></a>
/// </summary>
public static class BetweenExtensions
{

    /// <summary>
    /// Between check <![CDATA[min <= value <= max]]> 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">the value to check</param>
    /// <param name="min">Inclusive minimum border</param>
    /// <param name="max">Inclusive maximum border</param>
    /// <returns>return true if the value is between the min & max else false</returns>
    public static bool IsBetweenII<T>(this T value, T min, T max) where T:IComparable<T>
    {
        return (min.CompareTo(value) <= 0) && (value.CompareTo(max) <= 0);
    }

    /// <summary>
    /// Between check <![CDATA[min < value <= max]]>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">the value to check</param>
    /// <param name="min">Exclusive minimum border</param>
    /// <param name="max">Inclusive maximum border</param>
    /// <returns>return true if the value is between the min & max else false</returns>
    public static bool IsBetweenEI<T>(this T value, T min, T max) where T:IComparable<T>
    {
        return (min.CompareTo(value) < 0) && (value.CompareTo(max) <= 0);
    }

    /// <summary>
    /// between check <![CDATA[min <= value < max]]>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">the value to check</param>
    /// <param name="min">Inclusive minimum border</param>
    /// <param name="max">Exclusive maximum border</param>
    /// <returns>return true if the value is between the min & max else false</returns>
    public static bool IsBetweenIE<T>(this T value, T min, T max) where T:IComparable<T>
    {
        return (min.CompareTo(value) <= 0) && (value.CompareTo(max) < 0);
    }

    /// <summary>
    /// between check <![CDATA[min < value < max]]>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">the value to check</param>
    /// <param name="min">Exclusive minimum border</param>
    /// <param name="max">Exclusive maximum border</param>
    /// <returns>return true if the value is between the min & max else false</returns>

    public static bool IsBetweenEE<T>(this T value, T min, T max) where T:IComparable<T>
    {
        return (min.CompareTo(value) < 0) && (value.CompareTo(max) < 0);
    }
}

加上一些单元测试代码

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethodIsBeetween()
    {
        Assert.IsTrue(5.0.IsBetweenII(5.0, 5.0));
        Assert.IsFalse(5.0.IsBetweenEI(5.0, 5.0));
        Assert.IsFalse(5.0.IsBetweenIE(5.0, 5.0));
        Assert.IsFalse(5.0.IsBetweenEE(5.0, 5.0));

        Assert.IsTrue(5.0.IsBetweenII(4.9, 5.0));
        Assert.IsTrue(5.0.IsBetweenEI(4.9, 5.0));
        Assert.IsFalse(5.0.IsBetweenIE(4.9, 5.0));
        Assert.IsFalse(5.0.IsBetweenEE(4.9, 5.0));

        Assert.IsTrue(5.0.IsBetweenII(5.0, 5.1));
        Assert.IsFalse(5.0.IsBetweenEI(5.0, 5.1));
        Assert.IsTrue(5.0.IsBetweenIE(5.0, 5.1));
        Assert.IsFalse(5.0.IsBetweenEE(5.0, 5.1));

        Assert.IsTrue(5.0.IsBetweenII(4.9, 5.1));
        Assert.IsTrue(5.0.IsBetweenEI(4.9, 5.1));
        Assert.IsTrue(5.0.IsBetweenIE(4.9, 5.1));
        Assert.IsTrue(5.0.IsBetweenEE(4.9, 5.1));

        Assert.IsFalse(5.0.IsBetweenII(5.1, 4.9));
        Assert.IsFalse(5.0.IsBetweenEI(5.1, 4.9));
        Assert.IsFalse(5.0.IsBetweenIE(5.1, 4.9));
        Assert.IsFalse(5.0.IsBetweenEE(5.1, 4.9));

    }
}

答案 3 :(得分:20)

不,你必须单独测试每个端点。

if ((x > 0) && (x < 10)) {
   // do stuff
}

或者,如果您希望看起来更多“介于”之间“,请重新排序参数:

if ((0 < x) && (x < 10)) {
   // do stuff
}

答案 4 :(得分:15)

到目前为止,似乎没有一个答案考虑过动态的可能性,你不知道哪个值是下限和上限。对于一般情况,您可以创建自己的IsBetween方法,该方法可能类似于:

    public bool IsBetween(double testValue, double bound1, double bound2)
    {
        return (testValue >= Math.Min(bound1,bound2) && testValue <= Math.Max(bound1,bound2));
    }

答案 5 :(得分:9)

C#/ .NET中没有内置构造,​​但您可以轻松地为此添加自己的扩展方法:

public static class ExtensionsForInt32
{
    public static bool IsBetween (this int val, int low, int high)
    {
           return val > low && val < high;
    }
}

可以使用:

if (5.IsBetween (0, 10)) { /* Do something */ }

答案 6 :(得分:5)

在编译时验证的通用函数!

public static bool IsBetween<T>(this T item, T start, T end) where T : IComparable
{
    return item.CompareTo(start) >= 0 && item.CompareTo(end) <= 0;
}

答案 7 :(得分:4)

不会像

那么简单
0 < 5 && 5 < 10

所以我想如果你想要一个函数,你可以简单地将它添加到实用程序类:

public static bool Between(int num, int min, int max) {
    return min < num && num < max;
}

答案 8 :(得分:3)

int val_to_check = 5
bool in_range = Enumerable.Range(0, 13).Contains(val_to_check);

第二个参数是“count”而不是结束或高位数。

int low_num = 0
int high_num = 12
int val_to_check = 5
bool in_range = Enumerable.Range(low_num , high_num - low_num + 1).Contains(val_to_check);

检查val_to_check是否在0到12之间

答案 9 :(得分:3)

除了@Ed G的回答之外,所有答案都要求知道哪个边界是较低的边界,哪个边界是较高边界。

当你不知道哪个边界是哪个时,这是一种(非常明显的)做法。

  /// <summary>
  /// Method to test if a value is "between" two other values, when the relative magnitude of 
  /// the two other values is not known, i.e., number1 may be larger or smaller than number2. 
  /// The range is considered to be inclusive of the lower value and exclusive of the upper 
  /// value, irrespective of which parameter (number1 or number2) is the lower or upper value. 
  /// This implies that if number1 equals number2 then the result is always false.
  /// 
  /// This was extracted from a larger function that tests if a point is in a polygon:
  /// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
  /// </summary>
  /// <param name="testValue">value to be tested for being "between" the other two numbers</param>
  /// <param name="number1">one end of the range</param>
  /// <param name="number2">the other end of the range</param>
  /// <returns>true if testValue >= lower of the two numbers and less than upper of the two numbers,
  ///          false otherwise, incl. if number1 == number2</returns>
  private static bool IsInRange(T testValue, T number1, T number2)
  {
     return (testValue <= number1) != (testValue <= number2);
  }

注意:这不是一般方法;它是伪代码。上述方法中的T应该用适当的类型“int”或“float”或其他类型替换。 (有一些方法可以制作这种通用的,但它们非常混乱,以至于单线方法不值得,至少在大多数情况下都不行。)

答案 10 :(得分:1)

正如@Hellfrost指出的那样,在“一个操作”中将数字与两个不同的数字进行比较实际上是无稽之谈,而且我知道没有C#运算符封装它。

between = (0 < 5 && 5 < 10);

是我能想到的最紧凑的形式。

你可以使用extension制作一种有点“流畅”的方法(尽管有趣的是,我认为这有点过分了):

public static bool Between(this int x, int a, int b)
{
    return (a < x) && (x < b);
}

使用:

int x = 5;
bool b = x.Between(0,10);

答案 11 :(得分:1)

请参阅此链接。该问题的一线解决方案。

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

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

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

我知道这篇文章已经很老了,但它可能对其他人有所帮助......

答案 12 :(得分:0)

我不知道那个功能;无论如何,如果你的值是无符号的,只需要一个操作就意味着(val <11)...如果它被签名,我认为没有原子方法可以做到这一点,因为10不是2的幂...

答案 13 :(得分:0)

怎么样?
somenumber = Math.Max(0,Math.Min(10,somenumber));

答案 14 :(得分:0)

Base @Dan J这个版本不关心max / min,更像是sql:)

public static bool IsBetween(this decimal me, decimal a, decimal b, bool include = true)
{
    var left = Math.Min(a, b);
    var righ = Math.Max(a, b);

    return include
        ? (me >= left && me <= righ)
        : (me > left && me < righ)
    ;
}

答案 15 :(得分:0)

或者,如果要将值绑定到间隔:

public static T EnsureRange<T>(this T value, T min, T max) where T : IComparable<T>
    {
        if (value.CompareTo(min) < 0)
            return min;
        else if (value.CompareTo(max) > 0)
            return max;
        else
            return value;
    }

这就像双面Math.Min / Max

答案 16 :(得分:0)

对于负数值:

    Public Function IsBetween(Of T)(item As T, pStart As T, pEnd As T) As Boolean ' https://msdn.microsoft.com/fr-fr/library/bb384936.aspx
    Dim Deb As T = pStart
    Dim Fin As T = pEnd
    If (Comparer(Of T).Default.Compare(pStart, pEnd) > 0) Then Deb = pEnd : Fin = pStart
    Return Comparer(Of T).Default.Compare(item, Deb) >= 0 AndAlso Comparer(Of T).Default.Compare(item, Fin) <= 0
End Function