Click here to Skip to main content
15,892,746 members
Articles / Programming Languages / C#

Sorting an array of class objects on-the-fly

Rate me:
Please Sign up or sign in to vote.
1.29/5 (4 votes)
18 Aug 2009CPOL2 min read 20.8K   72   3   2
A class which allows you to sort an array of objects with just a sorting method.

Introduction

When I'm testing new applications, techniques, etc., I like having a standard set of data, usually a generic List of objects, that I can test with. Recently, I was testing a report generating library, and I found myself spending an annoying amount of time manipulating the data objects so that they would process in the correct order to test my report writer.

I added an IComparable interface to my class so that I could more easily change the printing order of the objects. This was okay, but if possible, I would like to avoid cluttering my classes with test code.

Since my policy as a programmer is that if I've had to do it more than a handful of times I should think about how to create a utility to do it, I decided to create a generic way to sort object arrays on the fly.

So I created a class which is basically a wrapper around another class for sorting purposes. There is a static method which accepts as parameters the array of objects and a delegate pointing to the sorting method. It creates an array of the sorting class, injecting the original objects into the sorting objects, runs the sort method, and recreates the array in the new order and returns it.

Background

The IComparable interface is used to create a sort order for an array of objects. If you add it to a class and implement it, you will get a single method, CompareTo. This method receives a single parameter, which is the object that you need to compare to the current object. An integer value is returned indicating whether the current object needs to be before or after the passed-in object in the array.

Using the Code

Once you download the cSorting class and make it available to your project, all you need is a sorting method. This method should take two parameters, which are the two objects to be sorted. It should return an integer value, which is:

  • < 0 if the first object comes before the second
  • > 0 if the second object comes before the second
  • = 0 if the objects are the same

Here's an example of a sorting method. We are assuming that we are working with an array of cPerson objects. The class cPerson has two string properties: name and birthState. We want the cPersons sorted by state of birth, and within each state, by name.

C#
public static int SortingByStateAndName(object x, object y) {
    // first, cast the two objects into their proper classes
    cPerson p1 = (cPerson)x;
    cPerson p2 = (cPerson)y;

    // alphabetical order of states
    int compare = String.Compare(p1.birthState, p2.birthState);
    // if the states are the same, compare the names
    if (compare == 0) {
        // ascending name order
        compare = String.Compare(p1.name, p2.name);
    }
    return compare;
}

Now, all you need to do is call the static sorting method:

C#
cPerson[] persons = CreateYourPersonArray();

// call the static method SortingThisArray, passing it the original
// array and a delegate pointing to the sorting method
cPerson[] newPersons = cSorting.SortingThisArray(persons, SortingByStateAndName);

Points of Interest

Even if you don't need to sort objects, it might be worth a peek into the cSorting class just to see how to use IComparable.

History

No changes yet.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Crystal Applications Software
United States United States
I've been a developer/analyst for over twenty years, hopping from language to language. C, in all its incarnations (K/R, Borland, C++, C#) is my preference.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Neem1219-Aug-09 4:36
Neem1219-Aug-09 4:36 
GeneralMy vote of 1 [modified] Pin
Guillaume Leparmentier18-Aug-09 13:54
Guillaume Leparmentier18-Aug-09 13:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.