If value in range(x,y) function c#

2019-06-22 06:26发布

问题:

Does c# have a function that returns a boolean for expression : if(value.inRange(-1.0,1.0)){}?

回答1:

Description

I suggest you use a extension method.

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

You can create this extension method in a generic way (thx to digEmAll and CodeInChaos, who suggest that). Then you can use that on every object that implements IComparable.

Solution

public static class IComparableExtension
{
    public static bool InRange<T>(this T value, T from, T to) where T : IComparable<T>
    {
        return value.CompareTo(from) >= 1 && value.CompareTo(to) <= -1;
    }
}

then you do this

double t = 0.5;
bool isInRange = t.InRange(-1.0, 1.0);

Update for perfectionists

After an extensive discussion with @CodeInChaos who said

I'd probably go with IsInOpenInterval as suggested in an earlier comment. But I'm not sure if programmers without a maths background will understand that terminology.

You can name the function IsInOpenInterval too.

More Information

  • MSDN - Extension Methods (C# Programming Guide)
  • MSDN - IComparable Interface


回答2:

Use Math.Abs(value) <= 1.0 for example



回答3:

Not very clear, but may be inverse:

Enumerable. Range(-1, 2).Any(x=>x==value).

By the way didn't compile this, writing from mobile.

edit

here I'm using Enumerable.Range

edit1

if we are talking about floating point numbers, it's enough to create an extension method which generates the sequence of numbers by specifying start number and offset step and after execute Any<T> on resulting collection, like in aswer provided.



标签: c# range