TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Sorting a Collection

Let's say I make a Person class and a People (collection) class based on the type Person. So I can sort just fine using the code below, but it seems like I'm missing something. Do I have to create helper classes within the collection class just to sort based on different fields? Is there a better way to do this. Ping me if you have a better way (code below)...

 

 

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);

            }

      }

}


Digg!

posted on Tuesday, August 10, 2004 8:37 PM

Feedback

# 为collection增加排序功能 8/19/2008 1:50 AM 峻祁连