By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,671 Members | 1,623 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,671 IT Pros & Developers. It's quick & easy.

Can you do a BinarySearch with an anonymous method?

P: n/a
I can do the following with Find:

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

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

int iktr = racers.BinarySearch(delegate(Racer racer) { return racer.Car ==
"Ferrari"; });

gives me these errors:

The best overloaded method match for
'System.Collections.Generic.List<Generics.Racer>.B inarySearch(Generics.Racer)'
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
Mar 11 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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.
Mar 11 '08 #2

P: n/a
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>.BinarySearch any more or
less brittle - it just makes it possible to call it without having to
write your own IComparer<Teach time.
Mar 11 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.