String Comparison in "CompareTo" Method

  • Thread starter Thread starter Fir5tSight
  • Start date Start date
F

Fir5tSight

Hi All,

I have an interface class defined as follows:

class FileName : IComparable
{
public FileName(string fileName, string packageName)
{
//
// TODO: Add constructor logic here
//
class FileName : IComparable
{
public FileName(string fileName, string packageName)
{
//
// TODO: Add constructor logic here
//
this.fileName = fileName;
this.packageName = packageName;

// missing unless visited to set to true
this.bVisited = false;
}

// Define how FileName objects are sorted
public int CompareTo(object other)
{
FileName otherFileObj = (FileName)other;
if (this.packageName < otherFileObj.packageName)
{
return (int)(this.packageName -
otherFileObj.packageName);
}
else if (this.packageName == otherFileObj.packageName)
{
return (int)(this.fileName - otherFileObj.fileName);
}
else
{
return (int)(otherFileObj.packageName -
this.packageName);
}
}


private string fileName;
private bool bVisited;
private string packageName;
}

I have trouble with the "CompareTo" method, because the operators '<'
or '-' can't be applied to string type. Anyone can advise me on how to
get this fixed?

I want to sort by packageName at first in the alphabetical order.
However, if two objects share a same packageName, then compare by
fileName, again in the alphabetical order.

Many thanks! This discussion forum has been so helpful to me.

-Emily
 
Emily,
I have trouble with the "CompareTo" method, because the operators '<'
or '-' can't be applied to string type. Anyone can advise me on how to
get this fixed?

Just delegate to String.CompareTo

public int CompareTo(object other)
{
FileName otherFileObj = (FileName)other;
int ret = this.packageName.CompareTo(otherFileObj.packageName);

if (ret == 0)
{
ret = this.fileName.CompareTo(otherFileObj.fileName);
}

return ret;
}


Mattias
 
Mattias Sjögren said:
Emily,


Just delegate to String.CompareTo

public int CompareTo(object other)
{
FileName otherFileObj = (FileName)other;
int ret = this.packageName.CompareTo(otherFileObj.packageName);

if (ret == 0)
{
ret = this.fileName.CompareTo(otherFileObj.fileName);
}

return ret;
}

Note that if you have quite a few comparisons to make, and you're using
..NET 2.0, you can improve readability using the null coalescing
operator:

http://msmvps.com/blogs/jon.skeet/archive/2006/07/28/106119.aspx
 
Back
Top