Programing

C #에 "중간"함수가 있습니까?

lottogame 2020. 11. 19. 07:46
반응형

C #에 "중간"함수가 있습니까?


Google은 "between"이 내가 찾고있는 함수의 이름임을 이해하지 못하며 관련성이없는 것을 반환합니다.

예 : 한 번의 작업으로 5가 0에서 10 사이인지 확인하고 싶습니다.


아니요,하지만 직접 작성할 수 있습니다.

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

"하나의 작업"이 의미하는 바는 명확하지 않지만 항목이 범위 내에 있는지 확인하기 위해 내가 아는 연산자 / 프레임 워크 방법이 없습니다.

물론 확장 방법을 직접 작성할 수 있습니다. 예를 들어, 다음은 두 끝점 에서 간격이 닫혀 있다고 가정하는 것 입니다.

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

여기에 완전한 수업이 있습니다.

/// <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));

    }
}

아니요, 각 엔드 포인트를 개별적으로 테스트해야합니다.

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

또는 더 "간단하게" 보이게 하려면 인수를 재정렬하십시오.

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

지금까지 어떤 답변도 동적으로 어떤 값이 하한과 상한인지 모를 가능성을 고려하지 않은 것 같습니다. 일반적인 경우에는 다음과 같은 고유 한 IsBetween 메서드를 만들 수 있습니다.

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

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 */ }

컴파일시 검증되는 일반 함수!

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

그렇게 간단하지 않을까요?

0 < 5 && 5 < 10

?

그래서 함수를 원한다면 유틸리티 클래스에 간단히 추가 할 수 있다고 생각합니다.

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

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

두 번째 매개 변수는 끝 또는 높은 숫자가 아닌 "개수"입니다.

IE

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 사이인지 확인합니다.


@Ed G의 답변을 제외하고 모든 답변은 어느 경계가 하한과 상한을 알아야합니다.

Here's a (rather non-obvious) way of doing it when you don't know which bound is which.

  /// <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);
  }

Note: This is NOT a generic method; it is pseudo code. The T in the above method should be replaced by a proper type, "int" or "float" or whatever. (There are ways of making this generic, but they're sufficiently messy that it's not worth while for a one-line method, at least not in most situations.)


Refer to this link. A one line solution to that question.

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

I know the post is pretty old, but It may help others..


As @Hellfrost pointed out, it is literally nonsense to compare a number to two different numbers in "one operation", and I know of no C# operator that encapsulates this.

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

Is about the most-compact form I can think of.

You could make a somewhat "fluent"-looking method using extension (though, while amusing, I think it's overkill):

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

Use:

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

I don't know that function; anyway if your value is unsigned, just one operation means (val < 11)... If it is signed, I think there is no atomic way to do it because 10 is not a power of 2...


What about

somenumber = Math.Max(0,Math.Min(10,somenumber));

Base @Dan J this version don't care max/min, more like 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)
    ;
}

Or if you want to bound the value to the interval:

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;
    }

It is like two-sided Math.Min/Max


And for negatives values:

    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

참고URL : https://stackoverflow.com/questions/5023213/is-there-a-between-function-in-c

반응형