String Array Sorting

By Fons Sonnemans, posted on
1399 Views

It took me today some time to figure out how to sort an array of strings case-sensitively. The default behavior of the Array.Sort() uses an default Comparer object which should be case-sensitive. When I tested this I found out that I had misinterpreted the definition of 'case-sensitive'. What I wanted was 'Oridinal' sorting. So I created an OrdinalStringComparer class which implements IComparer and I got what I wanted.

using System;
using System.Collections;

namespace ReflectionIT.Test {

   &nbspclass Class1{

   &nbsp   &nbsp[STAThread]
   &nbsp   &nbspstaticvoid Main(string[]args){

   &nbsp   &nbsp   &nbspTest(new CaseInsensitiveComparer());
   &nbsp   &nbsp   &nbspTest(Comparer.Default);   &nbsp   &nbsp
   &nbsp   &nbsp   &nbspTest(new OridinalStringComparer());
   &nbsp   &nbsp
   &nbsp   &nbsp   &nbspConsole.ReadLine();
   &nbsp   &nbsp}

   &nbsp   &nbspprivatestaticvoid Test(IComparer comparer){

   &nbsp   &nbsp   &nbspstring[]words=newstring[]{"c","a","A","aB","ab","Ab"};

   &nbsp   &nbsp   &nbspArray.Sort(words,comparer);
   &nbsp   &nbsp
   &nbsp   &nbsp   &nbspConsole.WriteLine(comparer.GetType().Name +":");
   &nbsp   &nbsp   &nbspforeach(stringwordinwords){
   &nbsp   &nbsp   &nbsp   &nbspConsole.WriteLine(word);
   &nbsp   &nbsp   &nbsp}
   &nbsp   &nbsp   &nbspConsole.WriteLine();
   &nbsp   &nbsp}
   &nbsp   &nbsp
   &nbsp}
   &nbsp   &nbsp
   &nbsppublicclass OridinalStringComparer : IComparer {
   &nbsp   &nbsp
   &nbsp   &nbspint IComparer.Compare(object x,object y ){
   &nbsp   &nbsp   &nbspreturnstring.CompareOrdinal((string)x,(string)y);
   &nbsp   &nbsp}
   &nbsp   &nbsp
   &nbsp}
   &nbsp   &nbsp
}

And when you run this program you get the following output:

CaseInsensitiveComparer:
A
a
Ab
ab
aB
c

Comparer:
a
A
ab
aB
Ab
c

OridinalStringComparer:
A
Ab
a
aB
ab
c

All postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.

Leave a comment

Blog comments

0 responses