How to sort elements of array list in C#

There are numerous sort methods in the framework including ArrayList.Sort. The problem is that they are all going to sort alphabetically and not numerically. You’ll need to write a custom sorter that understands numeric sorts.

Try the following (some argument checking left out for brevity)

public class NumericComparer : IComparer {
  public int Compare(object x, object y) {
    string left = (string)x; 
    string right = (string)y;
    int max = Math.Min(left.Length, right.Length);
    for ( int i = 0; i < max; i++ ) {
      if ( left[i] != right[i] ) { 
        return left[i] - right[i];
      }
    }
    return left.Length - right.Length;
  }
}

list.Sort(new NumericComparer());
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s