C# sort Arraylist strings alphabetical and on length

后端 未结 5 857
名媛妹妹
名媛妹妹 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: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();
    

提交回复
热议问题