有時可能有時排序的依據可能會需要參考到多個項目,
以學生座位排序為例,
我們可能參考到的排序依據有成績、身高、座號,
排序規則依序為:成績=>身高=>座號,
1. 成績不理想的學生坐前面
2. 身高較高的坐後面
3. 依座號作排序
當成績相等時,則比身高,
身高相等時,則比座號
以下為部分測試程式碼:
class Student
{
public string Name;
public int No;
public float Height;
public int Score;
public Student(string name,int no,float height,int score)
{
Name = name;
No = no;
Height = height;
Score =score;
}
public void ShowInfo()
{
Debug.Log("Name: " + Name + ", Score: " + Score + ", Height: " + Height + ", No: " + No);
}
}
void SortSeat()
{
List<Student> MyClass = new List<Student>();
MyClass.Add (new Student("Wilson",1,169,90));
MyClass.Add (new Student("Tom",2,180,40));
MyClass.Add (new Student("Anna",3,151,40));
MyClass.Add (new Student("Chris",4,151,40));
MyClass.Add (new Student("Alan",5,175,95));
MyClass.Sort((x,y)=>{ return x.Score.CompareTo(y.Score)*4 + x.Height.CompareTo(y.Height)*2 + x.No.CompareTo(y.No); });
for(int i =0;i<MyClass.Count;i++)
{
MyClass[i].ShowInfo();
}
}
//output------Name: Anna, Score: 40, Height: 151, No: 3
Name: Chris, Score: 40, Height: 151, No: 4
Name: Tom, Score: 40, Height: 180, No: 2
Name: Wilson, Score: 90, Height: 169, No: 1
Name: Alan, Score: 95, Height: 175, No: 5
//------------
小複習:Sort排序是由小到大
沒有留言:
張貼留言