binary search by predicate in csharp

main.cs
public static int BinarySearchByPredicate<T>(
    this IList<T> list, 
    Func<T, bool> predicate, 
    int startIndex = 0, 
    int endIndex = -1)
{
    endIndex = endIndex == -1 ? list.Count - 1 : endIndex;
 
    while (startIndex <= endIndex)
    {
        int mid = (startIndex + endIndex) / 2;
 
        if (predicate(list[mid]))
        {
            return mid;
        }
        else if (predicate(list[mid]))
        {
            endIndex = mid - 1;
        }
        else
        {
            startIndex = mid + 1;
        }
    }
 
    return -1;
}
563 chars
29 lines

This extension method can be used on any IList in C# and takes in a predicate function to determine the search condition. The function uses the standard binary search algorithm to search for the index of the first element that satisfies the predicate function. It returns -1 if no element is found. Optionally, you can specify the start and end index for the search.

gistlibby LogSnag