• 为collection增加排序功能


    注意到 CollectionBase.InnerList属性,这是一个protected 属性,得到一个包含了CollectionBase中的元素的ArrayList。

    所以可以调用ArrayList.Sort()来实现排序。

    using System;

     

    public class Person {

          public Person(string name, int age) {

                this.Name = name;

                this.Age = age;

          }

          public string Name;

          public int Age;

    }

     

    public class People : System.Collections.CollectionBase {

          public int Add(Person p) {

                return List.Add(p);

          }

     

          public void SortByName() {

                System.Collections.IComparer sorter = new NameSortHelper();

                InnerList.Sort(sorter);

          }

          public void SortByAge() {

                System.Collections.IComparer sorter = new AgeSortHelper();

                InnerList.Sort(sorter);

          }

     

          private class NameSortHelper : System.Collections.IComparer {

                public int Compare(object x, object y) {

                      Person p1 = (Person) x;

                      Person p2 = (Person) y;

                      return p1.Name.CompareTo(p2.Name);

                }

          }

     

          private class AgeSortHelper : System.Collections.IComparer {

                public int Compare(object x, object y) {

                      Person p1 = (Person) x;

                      Person p2 = (Person) y;

                      if(p1.Age > p2.Age)

                            return 1;

                      if(p1.Age < p2.Age)

                            return -1;

                      return 0;

                }

          }

    }

     

     

    class App {

          [STAThread]

          static void Main(string[] args) {

                People people = new People();

                people.Add(new Person("John" , 30));

                people.Add(new Person("Bob" , 20));

                people.Add(new Person("Zeke" , 18));

               

                //people.SortByAge();

                people.SortByName();

     

                foreach(Person p in people) {

                      Console.WriteLine("{0} , {1}", p.Name, p.Age);

                }

          }

    }

     

     

    http://unboxedsolutions.com/sean/archive/2004/08/10/292.aspx

    作者:峻祁连
    邮箱:junqilian@163.com
    出处:http://junqilian.cnblogs.com
    转载请保留此信息。
  • 相关阅读:
    lncRNA表达定量方法评估
    比对软件之STAR的使用方法
    怎么检测自己fastq的Phred类型 | phred33 phred64
    质控工具之TrimGalore使用方法
    怎么从bam文件中提取出比对OR没比对上的paired reads | bamToFastq | STAR
    RepBaseRepeatMaskerEdition下载 | RepeatMasker
    Nr,GenBank, RefSeq, UniProt 数据库的异同
    质控工具之cutadapt的使用方法
    初步了解hg19注释文件的内容 | gtf
    单细胞数据高级分析之消除细胞周期因素 | Removal of cell cycle effect
  • 原文地址:https://www.cnblogs.com/junqilian/p/1271203.html
Copyright © 2020-2023  润新知