3

I have class Employee and I need to implement IComparable and use CompareTo method to sort employees by name. From what I've seen, I have to return 1, -1, and 0, but how do I use the strings?

Here's what I have.

class Employee : IComparable<Employee>
{
    string name;
    string address;

    public int CompareTo(Employee obj) 
    {
        Employee person = obj;
    }
}
Steven Doggart
  • 43,358
  • 8
  • 68
  • 105
Xoax
  • 77
  • 4
  • 13
  • take a look at string.Compare https://msdn.microsoft.com/en-us/library/system.string.compare(v=vs.110).aspx – Oleksii Aza Jun 16 '17 at 02:54
  • 1
    Possible duplicate of [How to Implement IComparable interface?](https://stackoverflow.com/questions/4188013/how-to-implement-icomparable-interface) – Mahesh Jun 16 '17 at 02:55

2 Answers2

2

The easiest thing to do is to just pass it through to an already implemented comparison method. In this case, since you just need to compare two strings, you could just call String.Compare:

class Employee : IComparable<Employee>
{
    string name;
    string address;

    public int CompareTo(Employee obj) 
        => string.Compare(name, obj.name);    
}

You could use name.CompareTo(obj.name) too, but then you'd need to worry whether name might be null. According to the MSDN article on String.Compare:

One or both comparands can be null. By definition, any string, including the empty string (""), compares greater than a null reference; and two null references compare equal to each other.

Steven Doggart
  • 43,358
  • 8
  • 68
  • 105
0

Simple :

        public int CompareTo(Employee obj)
        {
            if (name == obj.name)
            {
                return address.CompareTo(obj.address);
            }
            return name.CompareTo(obj.name);
        }
jdweng
  • 33,250
  • 2
  • 15
  • 20