標籤:style blog color io ar for sp div on
#region實現IComparable的排序class UserInfo:IComparable<UserInfo> { public int ID { get; set; } public int Age { get; set; } public string Name { get; set; } public int CompareTo(UserInfo other) { if (this.Age > other.Age) return 1; return -1; } }//調用 List<UserInfo> lst = new List<UserInfo>(){ new UserInfo(){ID=1,Age=19,Name="張三"}, new UserInfo(){ID=2,Age=17,Name="李四"}, new UserInfo(){ID=3,Age=20,Name="王五"} }; lst.Sort(); for (int i = 0; i < lst.Count; i++) { Console.Write(lst[i].Name+":"+ lst[i].Age+"<"); }#endregion #region 實現IComparer的Sort排序class UserInfo_SortByID:IComparer<UserInfo> { public int Compare(UserInfo x, UserInfo y) { if (x.ID < y.ID) return 1; return -1; } } List<UserInfo> lst = new List<UserInfo>(){ new UserInfo(){ID=1,Age=19,Name="張三"}, new UserInfo(){ID=2,Age=17,Name="李四"}, new UserInfo(){ID=3,Age=20,Name="王五"} }; lst.Sort(new UserInfo_SortByID()); for (int i = 0; i < lst.Count; i++) { Console.Write(lst[i].Name+":"+ lst[i].Age+"<"); }#endregion
C# Sort排序