• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 527
  • Last Modified:

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.
0
thenthorn1010
Asked:
thenthorn1010
1 Solution
 
Mike TomlinsonMiddle 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

Featured Post

Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now