0
我想實現一個排序邏輯,如下所示:如果存在,請將華盛頓設置爲第一個邏輯。 下面的代碼工作良好。但是,我不關心城市不等於「華盛頓」,並想知道爲什麼我需要返回-1,並且不能返回0(意思是IComparable中的「等於」)?任何一個人都知道List <ICompareable> .Sort()是如何工作的?
P.S.我試過了,如果返回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;
}
}
}