How to Sort an ArrayList of Type Strings By One With Longest Length Being First to Shortest Length Being Last Using C#

I am attempting to sort an ArrayList of strings, and I was wondering if someone could help me find the sytanx to maybe use the ArrayList.Sort() function, if it will sort all of the string objects within the ArrayList from the longest length to the shortest length.

Any help with this issue would be greatly appreciated.
thenthorn1010Asked:
Who is Participating?
 
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
*I recommend the newer List<> instead of the ArrayList*

If you insist, though, try something like this:
public partial class Form1 : Form
    {

        private void button1_Click(object sender, EventArgs e)
        {
            ArrayList al = new ArrayList();
            al.Add("dog");
            al.Add("hamster");
            al.Add("fish");
            al.Add("lizard");
            al.Add("snake");

            MyComparer mc = new MyComparer();
            al.Sort(mc);

            foreach (Object x in al)
            {
                Console.WriteLine((string)x);
            }
        }

    }

    public class MyComparer : IComparer
    {

        int IComparer.Compare(object x, object y)
        {
            return ((string)y).Length.CompareTo(((string)x).Length);
        }

    }

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.