Question

I have an object named Artist.

public class Artist
{
    public string artistID { get; set; }
    public string artistName { get; set; }

    public Artist(string artistID, string artistName)
    {
        this.artistID = artistID;
        this.artistName = artistName;

    }

    public Artist()
    {
    }
    public Artist(string artistID)
    {
        this.artistID = artistID;
    }

Which has a custom Comparer like this:

public class CompareArtists : IComparer<Artist>
{

  public int Compare(Artist x, Artist y)
  {
      if (x.artistID == null) return -1;
      if (y.artistID == null) return 1;

    return String.Compare(x.artistID, y.artistID);
   }

}

I am trying to see whether an artist is contained in my list of artists in the main program. And I am doing that like this:

Artist tempArtist = new Artist(user[1]);
Artist result = new Artist();

position = artists.BinarySearch(tempArtist, dc);
result = artists.ElementAt(position);
                       users.ElementAt(counter).favoriteArtists.Add(result,Int32.Parse(user[2]));

The result of the binarysearch, is a negative number which from what I read on MSDN, is the complement of the next largest index. And it is shown when no results were found. However, I am 100% certain that the item I am searching for in my artists list does actually exist there. When I use a linear method, e.g. artists.Single or artists.Find, I get a result.

Do you see anything wrong with my comparer or the way I use binary search?

ps: dc is my comparer: CompareArtists dc = new CompareArtists(); and user[] is an array of strings that were split from a line I read with stream reader. it cotains the artist ID at [1] thanks in advance

Was it helpful?

Solution

You need to sort your list before BinarySearch, see documentation

Searches the entire sorted List for an element using the specified comparer and returns the zero-based index of the element.

artists.Sort(new CompareArtists());
position = artists.BinarySearch(tempArtist, dc);

Also you should use same comparer in Sort and BinarySearch to make it work

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top