(200-07-02) C#.NET 陣列 排序

摘要:(200-07-02) C#.NET 陣列 排序

基本類別 實作IComparable<Employee> 泛形介面

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace csmod03
{
    //實作介面
   public class Employee:IComparable<Employee>
    {
       //Data Field
        private String _id;

        public String Id
        {
            get { return _id; }
            set { _id = value; }
        }
        private String _name;

        public String Name
        {
            get { return _name; }
            set { _name = value; }
        }
        private Decimal _salary;

        public Decimal Salary
        {
            get { return _salary; }
            set {
                if (value > 0)
                {
                    _salary = value;
                }
            }
        }
       //建構子
       public Employee() { }
       //OverLoading
       public Employee(String _id, String _name, Decimal _salary)
       {
           this._id = _id;
           this._name = _name;
           if (_salary > 0)
           {
               this._salary = _salary;
           }
       }
       //解構子
     ~Employee()
       {
       }

     #region IComparable<Employee> 成員

     public int CompareTo(Employee other)
     {
         //定義比對值
         Int32 r = 0; //相等
         if (this._salary > other._salary)
         {
             r = -1; //往前排
         }
         if (this._salary < other._salary)
         {
             r = 1; //往後
         }
         return r;
     }

     #endregion
    }
}

 

主程式

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//員工陣列初始化
namespace csmod03
{
    class TesetEmployeeInitializer
    {
        public static void Main()
        {
            //定義區域變數
            Employee[] emps = new Employee[] { 
                new Employee("0001","eric",10000),
                //使用物件初始化 
                new Employee(){ Id="0002", Name="linda", Salary=50000},
                new Employee("0003","sam",30000)};

            System.Console.WriteLine(emps.Length);
            //輸出
            foreach (Employee e in emps)
            {
                System.Console.WriteLine(e.Salary);
            }
            //重新排序
            Array.Sort(emps);
            foreach (Employee e in emps)
            {
                System.Console.WriteLine(e.Salary);
            }

        }
    }
}