I've got a array of many strings. How can I sort the strings by alphabet?
Asked
Active
Viewed 3.5k times
3 Answers
21
Sounds like you just want to use the Array.Sort
method.
Array.Sort(myArray)
There are many overloads, some which take custom comparers (classes or delegates), but the default one should do the sorting alphabetically (ascending) as you seem to want.

Noldorin
- 144,213
- 56
- 264
- 302
-
1+1 for mentioning its only the default behaviour. It won't sort reverse alphabetically, you need to trick it or implement your own sort. – Adam Houldsworth Jun 30 '10 at 11:32
-
1Or just .Sort() if they are in a List – simendsjo Jun 30 '10 at 11:32
-
1+1 Excellent answer, for more complex sorting I would take a look at the IComparable interface or Linq's Sort expression – armannvg Jun 30 '10 at 12:45
2
Array.Sort also provides a Predicate-Overload. You can specify your sorting-behaviour there:
Array.Sort(myArray, (p, q) => p[0].CompareTo(q[0]));
You can also use LINQ to Sort your array:
string[] myArray = ...;
string[] sorted = myArray.OrderBy(o => o).ToArray();
LINQ also empoweres you to sort a 2D-Array:
string[,] myArray = ...;
string[,] sorted = myArray.OrderBy(o => o[ROWINDEX]).ThenBy(t => t[ROWINDEX]).ToArray();
The default sorting-behaviour of LINQ is also alphabetically. You can reverse this by using OrderByDescending() / ThenByDescending() instead.

0xDEADBEEF
- 3,401
- 8
- 37
- 66
2
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);
}
}
}

Gilad Green
- 36,708
- 7
- 61
- 95

Pranay Rana
- 175,020
- 35
- 237
- 263