Why doesn't List.BinarySearch () have overloads that compare <T> in addition to IComparer <T>?

I want to use List.BinarySearch()with a custom item type. The user type does not implement IComparable<T>; instead, I have several static Comparison<T>functions that I call, because at different points I want to sort the list according to different criteria. Plus, I think this adds clarity, since the sorting method can be described using the function name. Now I want to do a binary search in a list. I wanted to use one of my comparison functions, only to find that it List.BinarySearch()does not have an overload that accepts Comparison<T>, only IComparer<T>. I try to avoid IComparer<T>, because it seems silly to me a separate class for comparing objects. Why List.BinarySearch()doesn't it have overloads that take Comparison<T>in addition toIComparer<T>? And is it possible to use existing functions Comparison<T>in List.BinarySearch()?

+5
source share
3 answers

It is very easy to create IComparer<T>from Comparison<T>- here a (slightly modified) class from MiscUtil , which you are welcome to use:

/// <summary>
/// Utility to build an IComparer implementation from a Comparison delegate,
/// and a static method to do the reverse.
/// </summary>
public class ComparisonComparer<T> : IComparer<T>
{
    private readonly Comparison<T> comparison;

    public ComparisonComparer(Comparison<T> comparison)
    {
        if (comparison == null)
        {
            throw new ArgumentNullException("comparison");
        }
        this.comparison = comparison;
    }

    public int Compare(T x, T y)
    {
        return comparison(x, y);
    }
}

You can also add an extension method for List<T>to do this for you:

public static int BinarySearch<T>(this List<T> list, Comparison<T> comparison)
{
    return list.BinarySearch(new ComparisonComparer(comparison));
}
+11
source

Create a wrapper for Comparison, for example:

public class ComparisonWrapper<T> : IComparer<T>
{
    private Comparison<T> comparison;
    public ComparisonWrapper(Comparison<T> comparison)
    {
        this.comparison = comparison;
    }

    public int Compare(T x, T y)
    {
        return comparison(x, y);
    }
}
+1
source

Here the extension on Jon says it accepts a lambda expression.

public static class ListExtensions
{
    public static int BinarySearch<T>(this List<T> list, T item, Func<T, T, int> compare)
    {
        return list.BinarySearch(item, new ComparisonComparer<T>(compare));
    }
}

public class ComparisonComparer<T> : IComparer<T>
{
    private readonly Comparison<T> comparison;

    public ComparisonComparer(Func<T, T, int> compare)
    {
        if (compare == null)
        {
            throw new ArgumentNullException("comparison");
        }
        comparison = new Comparison<T>(compare);
    }

    public int Compare(T x, T y)
    {
        return comparison(x, y);
    }
}
0
source

All Articles