int[] arr = { 2, 3, 6, 1, 4, 5 };
Array.Sort(arr);
Array.ForEach(arr, i => Console.WriteLine(i)); // 1 2 3 4 5 6
public class Student : IComparable
{
public int Age { get; set; }
public string Name { get; set; }
public int Score { get; set; }
public int CompareTo(object obj)
{
if (obj is Student other) return Age.CompareTo(other.Age);
return 1;
}
}
直接 Array.Sort(students) 即可依 Age 排序。若未實作 IComparable,執行時拋出 InvalidOperationException。
public class StudentScoreComparer : IComparer
{
public int Compare(Student x, Student y) => x.Score.CompareTo(y.Score);
}
呼叫:Array.Sort(students, new StudentScoreComparer()); 依 Score 排序。
Array.Sort(students, (s1, s2) => s1.Score.CompareTo(s2.Score));
無需額外類別,適合一次性或簡單排序邏輯。
| 介面/委派 | 用途 | 特點 |
|---|---|---|
IComparable | 類別內建預設比較 | 單一排序規則,型別自身實作 |
IComparable<T> | 強型別版本 | 避免裝箱,建議優先實作 |
IComparer<T> | 外部比較器 (策略模式) | 多重排序規則、分離關注點 |
Comparison<T> | 委派形式比較 | Lambda/匿名方法,輕量彈性 |
using System;
using System.Collections.Generic;
namespace SortingInCSharp
{
class Program
{
public class Student : IComparable
{
public int Age { get; set; }
public string Name { get; set; }
public int Score { get; set; }
public int CompareTo(object obj) => obj is Student s ? Age.CompareTo(s.Age) : 1;
}
public class StudentScoreComparer : IComparer
{
public int Compare(Student x, Student y) => x.Score.CompareTo(y.Score);
}
static void Main()
{
var students = new[]
{
new Student { Age = 10, Name = "張三", Score = 70 },
new Student { Age = 12, Name = "李四", Score = 97 },
new Student { Age = 11, Name = "王五", Score = 80 },
new Student { Age = 9, Name = "趙六", Score = 66 },
new Student { Age = 12, Name = "司馬", Score = 90 }
};
Console.WriteLine("--- 預設排序 (Age) ---");
Array.Sort(students);
Print(students);
Console.WriteLine("--- 依 Score 排序 (IComparer) ---");
Array.Sort(students, new StudentScoreComparer());
Print(students);
Console.WriteLine("--- 依 Score 排序 (Lambda) ---");
Array.Sort(students, (s1, s2) => s1.Score.CompareTo(s2.Score));
Print(students);
Console.Read();
}
static void Print(Student[] arr) => Array.ForEach(arr, s => Console.WriteLine($"{s.Name}{s.Age,2}歲,分數{s.Score,3}"));
}
}
https://www.cnblogs.com/yukaizhao/archive/2011/08/19/csharp-compare.html