How to sort an array of strings alphabetically?

I have an array of several lines. How to sort strings alphabetically?

+7
sorting arrays c #
source share
3 answers

It looks like you just want to use the Array.Sort method.

 Array.Sort(myArray) 

There are many overloads, some of which accept user mappings (classes or delegates), but by default should be sorted alphabetically (ascending), as you think.

+19
source share
 class Program { static void Main() { string[] a = new string[] { "Egyptian", "Indian", "American", "Chinese", "Filipino", }; Array.Sort(a); foreach (string s in a) { Console.WriteLine(s); } } } 
+2
source share

Array.Sort also provides Predicate-Overload. Here you can specify your sorting behavior:

 Array.Sort(myArray, (p, q) => p[0].CompareTo(q[0])); 

You can also use LINQ to sort the array:

 string[] myArray = ...; string[] sorted = myArray.OrderBy(o => o).ToArray(); 

LINQ also allows you to sort a 2D array:

 string[,] myArray = ...; string[,] sorted = myArray.OrderBy(o => o[ROWINDEX]).ThenBy(t => t[ROWINDEX]).ToArray(); 

By default, LINQ sorting behavior is also performed alphabetically. You can undo this by using OrderByDescending () / ThenByDescending () instead.

+1
source share

All Articles