Buky <necunecu@xxxxxx> wrote:
> So, Let's say that I have an class with properies like Name, LastName & ID.
> I put them into List(of myClass) and I would like to search through that
> List based on my search criteria (Name & Id for example).
> So, I create an Comparer, and provide it's 'reference' to an BinarySearch
> functio, but each time I got incorrect results.
> Where could be problem in following code? Well:
1) BinarySearch only works if the list is already ordered to start
with, in an order which is consistent with the comparer you use.
2) Your comparer is inconsistent - in particular, if you do
Compare(x, y) and Compare(y, x) it could return a negative number
both times - meaning that x < y and y < x.
3) You appear to have finalizers for no reason, which is a generally
bad thing to do. (You also have public fields, but I'll assume
you wouldn't do that normally.)
If you make your comparer more sensible, and sort *passing in the
comparer* before calling BinarySearch it should work.
--
Jon Skeet - <skeet@xxxxxx>
Web site:
http://www.pobox.com/~skeet
Blog:
http://www.msmvps.com/jon.skeet
C# in Depth:
http://csharpindepth.com