Sort and BinarySearch on custom class?

  • Thread starter Thread starter Steven Blair
  • Start date Start date
S

Steven Blair

With the example below, would it be possible to perform a Sort, then a
BinarySearch on the structure?

I have achieved the same result using a <string> but not with a custom
type.
The Sort must be performed on the _id field and the BinarySearch will
scan for the _id and return _receivedMessage.

public class ReceivedMessage
{
protected string _id;
protected string _receivedMessage;

public string SearchField
{
get { return _id; }
}

public ReceivedMessage(string msg)
{
_receivedMessage = msg;

//First 6 chars is the id
_id = msg.Substring(0,6);

}

public override string ToString()
{
return _receivedMessage;
}
}

int Main()
{
List<ReceivedMessage> _receivedQueue = new List<ReceivedMessage>();

//Is it possible to Sort this, then perform a Binary search?
//I have achieve this using only <string> but not on a custom type.
}

Thanks in advance for the help.

Steven
 
Steven Blair said:
With the example below, would it be possible to perform a Sort, then a
BinarySearch on the structure?

I have achieved the same result using a <string> but not with a custom
type.
The Sort must be performed on the _id field and the BinarySearch will
scan for the _id and return _receivedMessage.

Yes - but you'll need appropriate comparisons. You could implement
IComparer<ReceivedMessage> to compare two ReceivedMessages by id, or
make ReceivedMessage implement IComparable<ReceivedMessage>. You'll
then need to pass the BinarySearch an IComparer<ReceivedMessage> as
well. You'll probably need to create a "dummy" ReceivedMessage with the
appropriate ID in order to search for another one with the same ID.
 
Back
Top