Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# sort Arraylist strings alphabetical and on length

I'm trying to sort an ArrayList of String.

Given:

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

Arraylist.Sort gives:

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

What I need is:

{A,B,C,AA,BB,CC}
like image 919
Michiel Blykers Avatar asked Dec 05 '22 13:12

Michiel Blykers


2 Answers

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 
like image 105
Ilya Ivanov Avatar answered Dec 16 '22 07:12

Ilya Ivanov


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();
like image 29
Icarus Avatar answered Dec 16 '22 07:12

Icarus