Click here to Skip to main content
Click here to Skip to main content

Sorting an array of class objects on-the-fly

By , 18 Aug 2009
 

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.

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:

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)

About the Author

Francine DeGrood Taylor
Web Developer Crystal Applications Software
United States United States
Member
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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberNeem1219 Aug '09 - 4:36 
tt
GeneralMy vote of 1 [modified]memberGuillaume Leparmentier18 Aug '09 - 13:54 
Sorry for the 1, but there's nothing new in your post and, as Joe Enos said, really badly designed.
 
The comparision cost of coding an IComparer (or even an anonymous delegate) and your solution is "merely" the same but IComparer solution is safer.
 
Why not using Array.Sort(T[] yourArray, Comparison compareMethodOrDelegate)?
 
modified on Tuesday, August 18, 2009 8:00 PM

GeneralMy vote of 1memberJoe Enos18 Aug '09 - 12:16 
Incredibly type-unsafe and very unnecessary. Array already includes methods for sorting using IComparer or Comparison.
 
Also, the cSorting class is shockingly bad. Wrapping objects around a cSorting object is unnecessary, there's a StringBuilder floating around in there for no apparent reason, and since you're using a static field for the delegate that's constantly changing, it's not thread-safe.

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 18 Aug 2009
Article Copyright 2009 by Francine DeGrood Taylor
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid