【C#】 List.Sort 方法
在C#中,List.Sort()不僅為系統自帶的變量(int, float, double …)類型的集合提供默認排序,還提供了自定義的排序方法。
List自帶排序
List<int> list = new List<int>();
list.Add(5);
list.Add(3);
list.Add(4);
list.Add(6);
list.Add(2);
list.Add(1);string str = "";
for(int i = 0; i < list.Count; i++)
{str += list[i].ToString() + " ";
}
Console.WriteLine(str);//輸出:5 3 4 6 2 1
str = "";
Console.WriteLine("--------------------------");
list.Sort();//排序
for (int i = 0; i < list.Count; i++)
{str += list[i].ToString() + " ";
}
Console.WriteLine(str);//輸出:1 2 3 4 5 6
str = "";
List自定義排序方式
1.繼承接口 IComparable,實現CompareTo()方法
class Item : IComparable<Item>
{private int m_atk;public int Atk{get{return m_atk;}}public Item(int atk){m_atk = atk;}public int CompareTo(Item other){//傳入的對象相當于0的位置//other = 傳入對象//小于0://放在傳入對象的前面//等于0://保持當前的位置不變//大于0://放在傳入對象的后面if (this.Atk > other.Atk){return 1;}else{return -1;}}
}
將此實例與CompareTo傳入的對象進行比較,并指示此實例在排序順序中時位于傳入對象之前、之后還是同一位置。
“值” | 條件 |
---|---|
<0 | 此實例位于 other 之前 |
=0 | 此實例在排序順序中的位置與 other 相同 |
>0 | 此實例位于 other 之后 |
List<Item> itemList = new List<Item>();
itemList.Add(new Item(4));
itemList.Add(new Item(1));
itemList.Add(new Item(3));
itemList.Add(new Item(2));
itemList.Add(new Item(5));itemList.Sort();//Item類必須繼承IComparable接口實現方法,否則報錯
for (int i = 0; i < itemList.Count; i++)
{str += itemList[i].Atk.ToString() + " ";
}
Console.WriteLine(str);//輸出:1 2 3 4 5
str = "";
2.在Sort中傳入 Comparison 委托函數,自定義比較方法
class Student
{private int m_stuId;public int StuId{get{return m_stuId;}}public Student(int stuId){m_stuId = stuId;}
}
List<Student> studentList = new List<Student>();
studentList.Add(new Student(20238802));
studentList.Add(new Student(20238803));
studentList.Add(new Student(20238804));
studentList.Add(new Student(20238805));
studentList.Add(new Student(20238801));
//studentList.Sort(SortStudent);studentList.Sort((stu1, stu2) =>
{if (stu1.StuId > stu2.StuId){return 1;}else{return -1;}
});for (int i = 0; i < studentList.Count; i++)
{str += studentList[i].StuId.ToString() + " ";
}
Console.WriteLine(str);//輸出:20238801 20238802 20238803 20238804 20238805
str = "";
因為作者精力有限,文章中難免出現一些錯漏,敬請廣大專家和網友批評、指正。