TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Maha
NA
0
326.4k
IComparable
Aug 20 2012 7:47 PM
This program is given in the following website (http://www.dotnetperls.com/icomparable). Salary is sorted by
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<Employee>
{
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<Employee> list = new List<Employee>();
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
*/
Reply
Answers (
8
)
Microsoft .NET libraries write directly to fields instead of using properties?
C# 2010 access a web service