C# sort Arraylist strings alphabetical and on length

后端 未结 5 725
名媛妹妹
名媛妹妹 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:30
    ArrayList list = new ArrayList {"A","C","AA","B","CC","BB"};
    
    var sorted = list.Cast<string>()
                     .OrderBy(str => str.Length)
                     .ThenBy(str => str);
    
    //LinqPad specific print call
    sorted.Dump();
    

    prints:

    A 
    B 
    C 
    AA 
    BB 
    CC 
    
    0 讨论(0)
  • 2021-01-19 05:38

    You could create an IComparable class taking in two Strings and sort them as follows:

    if (a.Length == b.Length)
        return String.Compare(a, b);
    return a.Length.CompareTo(b.Length);
    

    You may also want to handle null cases.

    0 讨论(0)
  • 2021-01-19 05:39

    It's easier to do this with Linq as so:

    string [] list = { "A","C","AA","B","CC","BB"};
    
    var sorted = list.OrderBy(x=>x.Length).ThenBy(x=>x);
    

    Note that the OrderBy method returns a new list. If you want to modify the original, then you need to re-assign it as so:

    list = list.OrderBy(x=>x.Length).ThenBy(x=>x).ToArray();
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-19 05:49

    I would suggest using the ToArray() method (or just using a List<string> instad of an ArrayList) to take advantage of the OrderBy and ThenBy functions. It would look something like this:

    list = list.OrderBy(/*Order it by length*/).ThenBy(/*Order alphabetically*/);
    
    0 讨论(0)
提交回复
热议问题