C# sort Arraylist strings alphabetical and on length

后端 未结 5 866
名媛妹妹
名媛妹妹 2021-01-19 05:14

I\'m trying to sort an ArrayList of String.

Given:

{A,C,AA,B,CC,BB}

Arraylist.Sort gives:

5条回答
  •  误落风尘
    2021-01-19 05:41

    This is kind of old school but, I went the IComparer Interface . . .

    public class SortAlphabetLength : System.Collections.IComparer
    {
        public int Compare(Object x, Object y)
        {
            if (x.ToString().Length == y.ToString().Length)
                return string.Compare(x.ToString(), y.ToString());
            else if (x.ToString().Length > y.ToString().Length)
                return 1;
            else
                return -1;
        }
    }
    

    and then test it . . .

    class Program
    {
        static void Main(string[] args)
        {
            ArrayList values = new ArrayList()
            {
                "A","AA","B","BB","C","CC"
            };
    
            SortAlphabetLength alphaLen = new SortAlphabetLength();
            values.Sort(alphaLen);
    
            foreach (string itm in values)
                Console.WriteLine(itm);
        }
    }
    

    output:

    A
    B
    C
    AA
    BB
    CC
    

提交回复
热议问题