为collection增加排序功能

本文介绍了一个自定义集合类People,该类继承自CollectionBase并实现了按Person对象的姓名和年龄进行排序的功能。通过使用InnerList属性获取ArrayList实例,并利用Sort方法配合自定义比较器完成排序。

 

注意到 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值