Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "between" function in C#?

Tags:

c#

Google doesn't understand that "between" is the name of the function I'm looking for and returns nothing relevant.

Ex: I want to check if 5 is between 0 and 10 in only one operation

like image 759
Mathieu Avatar asked Feb 16 '11 22:02

Mathieu


People also ask

How do you use between functions?

You might use Between... And to determine whether the value of a field falls within a specified numeric range. The following example determines whether an order was shipped to a location within a range of postal codes. If the postal code is between 98101 and 98199, the IIf function returns “Local”.


1 Answers

It isn't clear what you mean by "one operation", but no, there's no operator / framework method that I know of to determine if an item is within a range.

You could of course write an extension-method yourself. For example, here's one that assumes that the interval is closed on both end-points.

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

And then use it as:

bool b = 5.IsBetween(0, 10); // true 
like image 194
Ani Avatar answered Oct 12 '22 23:10

Ani