How to create a Between Extension Method

*爱你&永不变心* 提交于 2019-12-04 08:04:54
Arion

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

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

Maybe like this:

public static bool Between<T1, T2>(this T1 val1, T2 lowest, T2 highest) where T1 : IComparable where T2 : IComparable {
    return val1.CompareTo(lowest) > 0 && val1.CompareTo(highest) < 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!