Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Between Extension Method

I have a variable whose value is populated at runtime. I want to check whether that value is between two same datatype values (say lowest and highest) or not using an Extension Method.

I want to check like

int a = 2; //here static but is can be changed at runtime

if(a.Between(0,8))
   DoSomething();
else
   DoNothing();

If a is 0 or 8 or any value between them, it should return true.

If a is (-1 or less) or (9 or greater) then it should return false

i want to create an extension method like

public static bool Between<T1>(this T1 val1, T1 lowest, T1 highest) where ????
{
    What code to write here???? 
}
like image 486
Nikhil Agrawal Avatar asked May 09 '12 06:05

Nikhil Agrawal


2 Answers

You can do it like this:

public static bool Between<T>(this T actual, T lower, T upper) where T : IComparable<T>
{
    return actual.CompareTo(lower) >= 0 && actual.CompareTo(upper) <= 0;
}

Reference here

Or if you want to do it on a collection you can do this:

public static IEnumerable<TSource> Between<TSource, TResult>
(
    this IEnumerable<TSource> source, Func<TSource, TResult> selector,
    TResult lowest, TResult highest
)
    where TResult : IComparable<TResult>
{
    return source.OrderBy(selector).
        SkipWhile(s => selector.Invoke(s).CompareTo(lowest) < 0).
        TakeWhile(s => selector.Invoke(s).CompareTo(highest) <= 0 );
}

Reference here

Usage:

var tenTo40 = list.Between(s => s, 10, 40);
like image 63
Arion Avatar answered Sep 16 '22 12:09

Arion


Mixing types will make it harder, eg. if T1 is datetime and t2 is int then what behaviour do you expect?

Using only one type all the way you can use the IComparable interface

public static bool Between<T>(this T self, T lower,T higher) where T : IComparable
{
    return self.CompareTo(lower) >= 0 && self.CompareTo(higher) <= 0;
}
like image 29
Roger Johansson Avatar answered Sep 17 '22 12:09

Roger Johansson