String Array Sorting

By Fons Sonnemans, 27-4-2004

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 {

    class Class1 {

        [STAThread]
        static void Main(string[] args) {

            Test(new CaseInsensitiveComparer());
            Test(Comparer.Default);        
            Test(new OridinalStringComparer());
        
            Console.ReadLine();
        }

        private static void Test(IComparer comparer) {

            string[] words = new string[] { "c", "a", "A", "aB", "ab", "Ab" };

            Array.Sort(words, comparer);
        
            Console.WriteLine(comparer.GetType().Name + ":");
            foreach (string word in words) {
                Console.WriteLine(word);
            }
            Console.WriteLine();
        }
        
    }
        
    public class OridinalStringComparer : IComparer {
        
        int IComparer.Compare(object x, object y ) {
            return string.CompareOrdinal((string)x, (string)y);
        }
        
    }
        
}

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

Leave a Comment

Leave a Comment
Name
Comment
1 + 6 =

0 Comments

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.