return other.Salary.CompareTo(this.Salary);. Problem is highlighted in the program.
If we interchange "this.Salary" and "other.Salary" that means
return this.Salary.CompareTo(other.Salary);
the output(Salary) is arranged as follows (Low to High). Please explain the reason.
8000,Lucy
10000,Andrew
10000,Janet
10000,Steve
500000,Bill
using System;
using System.Collections.Generic;
class Employee : IComparable
{
public int Salary { get; set; }
public string Name { get; set; }
public int CompareTo(Employee other)
{
// Alphabetic sort if salary is equal. [A to Z]
if (this.Salary == other.Salary)
{
return this.Name.CompareTo(other.Name);
}
// Default to salary sort. [High to low]
return other.Salary.CompareTo(this.Salary);
}
public override string ToString()
{
// String representation.
return this.Salary.ToString() + "," + this.Name;
}
}
class Program
{
static void Main()
{
List
list.Add(new Employee() { Name = "Steve", Salary = 10000 });
list.Add(new Employee() { Name = "Janet", Salary = 10000 });
list.Add(new Employee() { Name = "Andrew", Salary = 10000 });
list.Add(new Employee() { Name = "Bill", Salary = 500000 });
list.Add(new Employee() { Name = "Lucy", Salary = 8000 });
// Uses IComparable.CompareTo()
list.Sort();
// Uses Employee.ToString
foreach (var element in list)
{
Console.WriteLine(element);
}
Console.ReadKey();
}
}
/*
500000,Bill
10000,Andrew
10000,Janet
10000,Steve
8000,Lucy
*/

VulpesRank #55 · 29.2K reputationPosted Aug 22, 2012, 2:53 AM EDT
VulpesRank #55 · 29.2K reputationPosted Aug 21, 2012, 1:02 AM EDT
Posted Aug 21, 2012, 6:34 AM EDT
I wish to know whether my understanding is correct.
VulpesRank #55 · 29.2K reputationPosted Aug 21, 2012, 7:34 AM EDT
However, as far as Employee.CompareTo(Employee) is concerned, 'this' is the current instance and 'other' is the parameter.
Posted Aug 21, 2012, 9:09 AM EDT
VulpesRank #55 · 29.2K reputationPosted Aug 22, 2012, 1:04 AM EDT
Do you mean an example which calls them directly, rather than indirectly when sorting a list?
Posted Aug 22, 2012, 2:15 AM EDT
Posted Aug 22, 2012, 2:59 AM EDT