陣列可以透過Static Method Array.Sort來達到排序的目的.
(1) C# 基礎型別(Primitive types :int, double or string)
Int Array :
int[] intArray = new int[5] { 8, 10, 2, 6, 3 };
Array.Sort(intArray);
foreach (int i in intArray)
Console.Write(i + " ");
輸出: 2 3 6 8 10
String Array :
string[] stringArray = new string[5] { "X", "B", "Z", "Y", "A" };
Array.Sort(stringArray);
foreach (string str in stringArray)
Console.Write(str + " ");
輸出: A B X Y Z
(2)透過Delegate對自訂型別排序
定義類別
class User
{
public string Name;
public int Age;
public User(string Name, int Age)
{
this.Name = Name;
this.Age = Age;
}
}
定義使用者資料
User[] users = new User[3]
{ new User("Betty", 23),
new User("Susan", 20),
new User("Lisa", 25)
};
//根據姓名排序 Inline delegate
Array.Sort(users, delegate(User user1, User user2)
{
return user1.Name.CompareTo(user2.Name);
}
);
foreach (User user in users)
Console.Write(user.Name + ":" + user.Age + " ");
輸出: Betty:23 Lisa:25 Susan:20
//根據年齡排序 Method Delegate
delegate int mySort(User user1, User user2);
…
Array.Sort(users, mySortMethod);
foreach (User user in users)
Console.Write(user.Name + ":" + user.Age + " ");
…
private int mySortMethod(User user1, User user2)
{
return user1.Age.CompareTo(user2.Age);
}
輸出: Susan20 Betty23 Lisa25)
(3)透過IComparable對自訂型別排序
定義類別
public class User : IComparable
{
public string Name;
public int Age;
public User(string Name, int Age)
{
this.Name = Name;
this.Age = Age;
}
// implement IComparable interface
public int CompareTo(object obj)
{
if (obj is User)
{
return this.Name.CompareTo((obj as User).Name);//根據姓名排序
}
throw new ArgumentException("Object is not a User");
}
}
定義使用者資料
User[] users = new User[3]
{ new User("Betty", 23),
new User("Susan", 20),
new User("Lisa", 25)
};
//根據姓名排序
Array.Sort(users);
0 個回應:
張貼留言