I want to implement a sort logic as: Set Washington as first if exists.
The following code works good.However,I’m not caring about cities not equals “Washington” and wondering why I need return -1 and could not return 0(meaning “equals” in IComparable)?
P.S. I have tried it, “Chicago” will be first if return 0.
class Program
{
static void Main(string[] args)
{
List<City> cityList = new List<City>()
{
new City(){Name = "New York"},
new City(){Name ="Los Angeles"},
new City(){Name="Washington"},
new City(){Name="Chicago"}
};
cityList.Sort();
}
}
public class City: IComparable
{
public string Name { get; set; }
public int CompareTo(object obj)
{
if ((obj as City).Name == "Washington")
{
return 1;
}
else
{
return -1;
}
}
}
Returning 0 means the string are equal.
If you return 0 whenever obj is not “Washington”, sometimes “Washington” will be in the current instance you are comparing obj with. This will prevent Washington rising to the top.