歡迎跟我連絡

本頁最下方有Web MSN可以直接跟我交談喔!
免安裝程式...哈哈 歡迎聊天

2009年8月26日 星期三

陣列排序(Arrays Sorting) in C#

陣列可以透過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);

 

2009-8-12 下午 01-02-48

0 個回應:

MSN狀態(我在線上時,可以跟我交談喔)