List 的Sort方法排序有三種結(jié)果 1,0,-1分別表示大于,等于,小于。
1.對于數(shù)值類型的List (List<int>),直接使用Sort進(jìn)行排序。
- List<int> scoreList=new List<int>(){89,100,78,23,67};
-
- scoreList.Sort();//默認(rèn)按升序排列,相當(dāng)于:scoreList.Sort((x,y)=>x.CompareTo(y))
-
- scoreList.Sort((x,y)=>-x.CompareTo(y));//降序排列
2.對于非數(shù)值類型或者自定義類型,可通過實(shí)現(xiàn)IComparable接口重寫CompareTo方法來排序:
- public class Person : IComparable<Person>
- {
- public string Name { get; set; }
- public int Age { get; set; }
-
- //ComparetTo:大于 1; 等于 0; 小于 -1;
- public int CompareTo(Person p)
- {
- int result;
- if (this.Name == p.Name && this.Age == p.Age)
- {
- result = 0;
- }
- else
- {
- //this.Name表示后面的 Mary p.Name表示前面的 Bob
- //Mary 跟Bob 由小到大比較,如果Mary 與 Bob 比較 大于0(說明Mary 大于Bob),則 result=1(說明是由小到大的順序)
- if (this.Name.CompareTo(p.Name) > 0)//先按名字小到大排列
- {
- result = 1;
- }
- else if (this.Name == p.Name && this.Age > p.Age)//名字相同則按年齡由小到大排列
- {
- result = 1;
- }
- else
- {
- result = -1;
- }
- }
- return result;
- }
-
- public override string ToString()
- {
- return this.Name + "-" + this.Age;
- }
- }
- List<Person> lstPerson = new List<Person>();
- lstPerson.Add(new Person() { Name = "Bob", Age = 19 });
- lstPerson.Add(new Person() { Name = "Mary", Age = 18 });
- lstPerson.Add(new Person() { Name = "Mary", Age = 17 });
- lstPerson.Add(new Person() { Name = "Lily", Age = 20 });
- lstPerson.Sort();
- foreach (Person item in lstPerson)
- {
- Console.WriteLine(item.ToString());
- }
- Console.ReadKey();
輸出:Bob-19 Lily-20 Mary-17 Mary-18
或不實(shí)現(xiàn)IComparable接口而使用linq排序:
- List<Person> lstPerson = new List<Person>();
- lstPerson.Add(new Person() { Name = "Bob", Age = 19 });
- lstPerson.Add(new Person() { Name = "Mary", Age = 18 });
- lstPerson.Add(new Person() { Name = "Mary", Age = 17 });
- lstPerson.Add(new Person() { Name = "Lily", Age = 20 });
- lstPerson.Sort();
-
- lstPerson.Sort((x, y) => {
- int result;
- if (x.Name == y.Name && x.Age == y.Age)
- {
- result = 0;
- }
- else
- {
- if (x.Name.CompareTo(y.Name) > 0)
- {
- result = 1;
- }
- else if (x.Name == y.Name && x.Age > y.Age)
- {
- result = 1;
- }
- else
- {
- result = -1;
- }
- }
- return result;
- });
-
-
- foreach (Person item in lstPerson)
- {
- Console.WriteLine(item.ToString());
- }
- Console.ReadKey();
輸出:Bob-19 Lily-20 Mary-17 Mary-18
|