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.Collections;
namespace ReflectionIT.Test {
 class Class1{
   [STAThread]
   staticvoid Main(string[]args){
     Test(new CaseInsensitiveComparer());
     Test(Comparer.Default);    
     Test(new OridinalStringComparer());
   
     Console.ReadLine();
   }
   privatestaticvoid Test(IComparer comparer){
     string[]words=newstring[]{"c","a","A","aB","ab","Ab"};
     Array.Sort(words,comparer);
   
     Console.WriteLine(comparer.GetType().Name +":");
     foreach(stringwordinwords){
       Console.WriteLine(word);
     }
     Console.WriteLine();
   }
   
 }
   
 publicclass OridinalStringComparer : IComparer {
   
   int IComparer.Compare(object x,object y ){
     returnstring.CompareOrdinal((string)x,(string)y);
   }
   
 }
   
}
And when you run this program you get the following output:
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.
Blog comments
0 responses