Can you do a BinarySearch with an anonymous method?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • tshad

    Can you do a BinarySearch with an anonymous method?

    I can do the following with Find:

    Racer theRacer2 = racers.Find(del egate(Racer racer) { return racer.Car ==
    "Ferrari"; });

    But I can't seem to do the same with BinarySearch, this:

    int iktr = racers.BinarySe arch(delegate(R acer racer) { return racer.Car ==
    "Ferrari"; });

    gives me these errors:

    The best overloaded method match for
    'System.Collect ions.Generic.Li st<Generics.Rac er>.BinarySearc h(Generics.Race r)'
    has some invalid arguments

    and

    Argument '1': cannot convert from 'anonymous method' to 'Generics.Racer '

    Can I make this work with an anonymous method or do I need to create another
    function to use BinarySearch?

    Thanks,

    Tom


  • Ben Voigt [C++ MVP]

    #2
    Re: Can you do a BinarySearch with an anonymous method?

    Marc Gravell wrote:
    Here you go - a C# 3 version amenable to binary-search on a sub-
    property; actually it should work in C# 2 given a few minor changes,
    but anonymous methods aren't as appealing as lambdas, and the
    extension methods and improved type inference really help us here...
    There's a problem using BinarySearch like that... it's fragile. The list
    has to be sorted by the same comparer used for binary search.

    Instead, use a SortedList, where the comparer is kept with the list and
    can't become inconsistent between sorting and searching.


    Comment

    • Marc Gravell

      #3
      Re: Can you do a BinarySearch with an anonymous method?

      There's a problem using BinarySearch like that... it's fragile.  The list
      has to be sorted by the same comparer used for binary search.
      Yes, but it is hard to get around that and keep with a simple List<T>;
      changing to SortedList<TKey ,TValueisn't necessarily trivial,
      especially if you to allow different sorting (which may necessitate
      different TKey).

      Or put another way - it doesn't make List<T>.BinaryS earch any more or
      less brittle - it just makes it possible to call it without having to
      write your own IComparer<Teach time.

      Comment

      Working...