ExtensionMethod.NET Home of 818 C#, Visual Basic, F# and Javascript extension methods

Between

c# version of "Between" clause of sql query with including option

Source

public static bool Between<T>(this T item, T start, T end, bool includeStart = true, bool includeEnd = true)
{
    return 
        (
            (includeStart && Comparer<T>.Default.Compare(item, start) >= 0)
            ||
            (!includeStart && Comparer<T>.Default.Compare(item, start) > 0)
        )
        &&
        (
            (includeEnd && Comparer<T>.Default.Compare(item, end) <= 0)
            ||
            (!includeEnd && Comparer<T>.Default.Compare(item, end) < 0)
        );
}

Example

int start = 10;
int end = 20;
int num = 10;

bool isBetween = num.Between(start, end);
bool isNotBetween = num.Between(start, end, false, false);

Author: mousoft

Submitted on: 29 apr 2019

Language: C#

Type: Between

Views: 781