Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort a string array by alphabet?

Tags:

arrays

c#

sorting

I've got a array of many strings. How can I sort the strings by alphabet?

like image 397
eagle999 Avatar asked Jun 30 '10 11:06

eagle999


3 Answers

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.

like image 79
Noldorin Avatar answered Oct 06 '22 16:10

Noldorin


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.

like image 33
0xDEADBEEF Avatar answered Oct 06 '22 16:10

0xDEADBEEF


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);
        }
    }
}
like image 37
Pranay Rana Avatar answered Oct 06 '22 15:10

Pranay Rana