今天是學(xué)習(xí)C#第17天。。。
今天沒有學(xué)習(xí)新東西,在做項(xiàng)目,但昨天昨天在做作業(yè)時(shí)用到了一個(gè)很好用的排序接口IComparable<Student>。
說它之前,先回憶一下冒泡排序。
冒泡排序:
兩個(gè)變量或兩個(gè)數(shù)組元素相互交換數(shù)據(jù):
int a = 10, b = 20;
//將a值賦給中間變量
int temp = a;//a最開始時(shí)的值:10
a = b;
b = temp;
//賦值給臨時(shí)變量
temp = numbers[0];//1
numbers[0] = numbers[3];//-1
numbers[3] = temp;//1
排序:
bool complete;
//輪次 == 數(shù)組長度 - 1
for (int i = 0; i < numbers.Length - 1; i++)
{
complete = true;
//比較的次數(shù)
for (int j = 0; j < numbers.Length - i - 1; j++)
{
//從小到大
// if(numbers[j] > numbers[j+1])
//從大到小
// if(numbers[j] < numbers[j+1])
//前大后小,交換
if (numbers[j] > numbers[j + 1])
{
//排序還沒有完成
complete = false;
//臨時(shí)存儲(chǔ)
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
//如果已經(jīng)完成了排序,則跳出外層循環(huán),結(jié)束排序
if(complete)
break;
}
冒泡排序是最簡單的排序方法,可以通過兩兩比較進(jìn)行排序
IComparable<Student>接口:
定義由值類型或類實(shí)現(xiàn)的通用比較方法,旨在創(chuàng)建特定于類型的比較方法以對(duì)實(shí)例進(jìn)行排序。
使用IComparable<Student>接口我們可以很快實(shí)現(xiàn)排序
public class Student : IComparable<Student>
{
public int CompareTo(Student other)
{
}
}
CompareTo返回值int的含義:
| “值” | 含義 |
|---|---|
| 小于零 | 此對(duì)象 CompareTo 在排序順序中位于方法所指定的對(duì)象之前。 |
| 零 | 此當(dāng)前實(shí)例在排序順序中與方法參數(shù)指定的對(duì)象出現(xiàn)在同一位置 CompareTo 。 |
| 大于零 | 此當(dāng)前實(shí)例 CompareTo 位于排序順序中由方法自變量指定的對(duì)象之后。 |
/// <summary>
/// 科目枚舉
/// </summary>
public enum SubjectType
{
Math,
Chinese,
English
}
public class Student : IComparable<Student>
{
public string name;
public char sex;
public byte age;
public int studentNumber;
/// <summary>
/// 地址
/// </summary>
public string site;
/// <summary>
/// 成績<科目,分?jǐn)?shù)>
/// </summary>
public Dictionary<SubjectType, byte> scores;
public Student(string name, char sex, byte age, int studentNumber, string site)
{
this.name = name;
this.sex = sex;
this.age = age;
this.studentNumber = studentNumber;
this.site = site;
scores = new Dictionary<SubjectType, byte>();
}
public void AddScore(SubjectType subjectType, byte score)
{
scores.Add(subjectType, score);
}
public int CompareTo(Student other)
{
//根據(jù)年齡進(jìn)行排序 ,升序排序,大于other對(duì)象返回1,將其放在other對(duì)象的后面
if (this.age > other.age)
{
return 1;
}
else if (this.age < other.age)
{
return -1;
}
else
{
return 0;
}
//根據(jù)成績排序,數(shù)學(xué)一樣就比語文,語文還一樣就比英語
// foreach (var item in scores)
// {
// if (item.Value > other.scores[item.Key])
// {
// return -1;
// }
// else if (item.Value < other.scores[item.Key])
// {
// return 1;
// }
// }
// return 0;
}
}
進(jìn)行比較后,可以通過Sort()排序
例:
List<Student> students = new List<Student>(Students.Values);
Students .Sort();