C # sort Arraylist strings alphabetically and by length

I am trying to sort an ArrayList from a String .

Given:

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

Arraylist.Sort gives:

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

What I need:

 {A,B,C,AA,BB,CC} 
+4
source share
5 answers

This is a kind of old school, but I went to 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 check it out.,.

 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
source
 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:

 ABC AA BB CC 
+12
source

This is easier to do with Linq like this:

 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 change the original, you need to assign it as follows:

 list = list.OrderBy(x=>x.Length).ThenBy(x=>x).ToArray(); 
+4
source

I would suggest using the ToArray() method (or just using the List<string> instad ArrayList) to use the ThenBy and ThenBy . It will look something like this:

 list = list.OrderBy(/*Order it by length*/).ThenBy(/*Order alphabetically*/); 
0
source

You can create the IComparable class using two lines and sort them as follows:

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

You can also handle null cases.

0
source

All Articles