现在的位置: 首页 > 综合 > 正文

利用比较器接口实现类排序

2013年11月19日 ⁄ 综合 ⁄ 共 1284字 ⁄ 字号 评论关闭

听了全老师的一堂关于java集合框架的课,感觉受益匪浅。虽然自己玩了这么久的程序设计也做过不少的项目,如果要做排序的话肯定还是会向大学课本上教的的那样用什么排序算法来实现。java可以通过集合框架来完成。那么Net呢?我于是重新把全老师讲的那道关于学生类排序的题目用Net写了一边

using System;
using System.Collections.Generic;
using System.Collections;

namespace Ic
{
    //学生类 我希望根据年龄来排序
    public class  Students : IComparer//比较器接口
    {
        private string _strName=string.Empty;
        private int    _intAge=0;
        
        public Students()
        {
            
        }
        
        public Students(string name ,int age)
        {
            this._strName=name;
            this._intAge=age;
        }
        
        //比较两个对象并返回一个值,指示一个对象是小于、等于还是大于另一个对象。
        public int Compare(object x ,object y)
        {            
            Students xs=x as Students;
            Students ys=y as Students;
            
            if (xs==null || ys==null)
                throw new Exception ("转换错误");
            
            int Retval=0;
            if (xs._intAge>ys._intAge)
                Retval=1; 
            if (xs._intAge<ys._intAge)
                Retval=-1;
            
            return Retval;
        }
        //重写父类object的ToString()方法
        public override string ToString()
        {
            return this._strName+ " " + this._intAge+"" ;
        }
    }
    
    
    
    public class MainClass
    {
        public static void Main(string[] args)
        {
            Students s1=new Students("张三",19);
            Students s2=new Students("李四",9);
            Students s3=new Students("王五",39);
            Students s4=new Students("蛋炒饭",12);
            ArrayList al=new ArrayList();
            al.Add(s1);
            al.Add(s2);
            al.Add(s3);
            al.Add(s4);
            
            IComparer myComparer = new Students();
            al.Sort(myComparer);//根据比较器对所有元素进行排序
            //Console.WriteLine(al.ToString());
            
            //枚举器
            System.Collections.IEnumerator myIEnm= al.GetEnumerator();
            
            while (myIEnm.MoveNext())
            {
                Console.WriteLine(myIEnm.Current.ToString());
            }
            
            Console.Read();
        }
        
        
        
    }
}

抱歉!评论已关闭.