zoukankan      html  css  js  c++  java
  • 使类支持排序

      1using System;
      2using System.Collections.Generic;
      3using System.Text;
      4using System.Collections;
      5
      6namespace ConsoleApplication1
      7{
      8    /// <summary>
      9    /// 继承IComparable接口,使类可以支持排序,排序的算法在Array类中
     10    /// </summary>

     11    public class Student : IComparable 
     12    {
     13        private string m_Name;
     14        private int m_Score;
     15
     16        public Student() { }
     17
     18        public Student(string name, int score) 
     19        {
     20            this.m_Name = name;
     21            this.m_Score = score;
     22        }

     23
     24        public string Name
     25        {
     26            get return m_Name; }
     27            set { m_Name = value; }
     28        }

     29
     30        public int Score
     31        {
     32            get return m_Score; }
     33            set { m_Score = value; }
     34        }

     35
     36        IComparable 成员
     65      
     66    }

     67
     68    public class StudentSortByName :  IComparer 
     69    {
     70
     71        IComparer 成员
     91    }

     92
     93    class Program
     94    {
     95        static void Main(string[] args)
     96        {
     97            Student[] students = new Student[10];
     98            Random rd = new Random();
     99            for (int i = 0; i < 10; i++
    100            {
    101                students[i] = new Student("Student" + i.ToString(), rd.Next(100));
    102            }

    103            Console.WriteLine("分数从小到大排序");
    104            Array.Sort(students);
    105            ShowStudents(students);
    106
    107            Console.WriteLine("分数从大到小排序");
    108            Array.Reverse(students);
    109            ShowStudents(students);
    110
    111            Console.WriteLine("以学生名称排序");
    112            Array.Sort(students, new StudentSortByName());
    113            ShowStudents(students);
    114            Console.ReadLine();
    115
    116
    117        }

    118
    119        private static void ShowStudents(Student[] students)
    120        {
    121            foreach (Student s in students)
    122            {
    123                Console.WriteLine("Name :" + s.Name + " Score :" + s.Score.ToString());
    124            }

    125        }

    126    }

    127}

    128
  • 相关阅读:
    Trojan.DL.Agent.nxd和RootKit.Agent.yj木马清除
    Java中的格式化数值(eg:保留两位小数)
    Int16, Int32, Int64的一点感悟
    在win2003上设置asp网站
    WPF学习笔记.
    对WF工作流异常(Event on interface type for instance id cannot be delivered)的一点总结.
    创建,安装,调试 Windows Service
    灵活而又可怕的params参数数组
    (转) 输入码、区位码、国标码与机内码
    SQL Server 2008 未来将不再包含全文检索功能, 再研究此功能已经没多大意思了.
  • 原文地址:https://www.cnblogs.com/ghx88/p/879302.html
Copyright © 2011-2022 走看看