problem with using CompareTo when having string

T

Tony

Hello!

I have method CompareTo written below. But I have a problem because I want
to sort on HeatNumber which is of type int and if this is the same on
MspName
which is a string. But according to the compiler I'm not allowed to use < on
string.
So my question is how do I solve this problem. The object Item is stored in
an ArrayList.

public int CompareTo(object right)
{
if (right is Item)
{
Item item = right as Item;
if (this.HeatNumber == item.HeatNumber) // same chargenumber
{
if (this.MspName < item.MspName)
return -1;
else if (this.MspName == item.MspName) // same sop
return 0;
else
return 1;
}
else
{
return this.HeatNumber - item.HeatNumber;
}
}
else
{
throw new ArgumentException("Object to compare is not a Item
object");
}
}

//Tony
 
M

Morten Wennevik [C# MVP]

Hi Tony,

Would you be looking for something like:

public int CompareTo(object right)
{
if (right is Item)
{
Item item = right as Item;

if (this.HeatNumber != item.HeatNumber)
return this.HeatNumber.CompareTo(item.HeatNumber);
else
return this.MspName.CompareTo(item.MspName);
}
else
{
throw new ArgumentException("Object to compare is not a Item object");
}
}

By the way. Consider using a List<Item> instead of arraylist and have Item
implement IComparable<Item>. That way you don't have to check and cast the
object.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top