Search code examples
stringsortingicomparable

Sorting an array of strings by length using IComparable<string>


I am missing something small here to sort an array of strings by their length using Array.Sort and IComparable<T>. The int CompareTo(string) method just won't get overloaded.

public class Program : IComparable
{

    public int CompareTo(string obj)//trying to redefine CompareTo for the Array.Sort method
    {

        if (this.ToString().Length > obj.ToString().Length)
            return 1;
        if (this.ToString().Length < obj.ToString().Length)
            return -1;
        if (this.ToString().Length == obj.ToString().Length)
            return 0;
        else
            throw new Exception();

    }

    static void Main(string[] args)
    {
        //to sort by length:
        string[] arrayStrings = { "a", "b", "the", "roof", "is", "on", "fire" };
        Array.Sort(arrayStrings);//instead comes sorted alphbetically
        foreach (var item in arrayStrings)
        {
            Console.WriteLine(item);
        }
    }
}

Solution

  • Instead of trying to override the CompareTo method on the string class (which you can't do anyway because the string class is sealed), create an IComparer<string> class and pass an instance of that to Arrays.Sort().

    public class StringLengthComparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            if (x.Length > y.Length) 
                return 1;
    
            if (x.Length < y.Length) 
                return -1;
    
            return 0;
        }
    }
    
    public class Program
    {
        static void Main(string[] args)
        {
            string[] arrayStrings = 
                     new string[] { "a", "b", "the", "roof", "is", "on", "fire" };
    
            Array.Sort(arrayStrings, new StringLengthComparer());
    
            foreach (var item in arrayStrings)
            {
                Console.WriteLine(item);
            }
        }
    }
    

    Output:

    a
    b
    is
    on
    the
    roof
    fire