11

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

3 Answers 3

24

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for mentioning its only the default behaviour. It won't sort reverse alphabetically, you need to trick it or implement your own sort.
Or just .Sort() if they are in a List
+1 Excellent answer, for more complex sorting I would take a look at the IComparable interface or Linq's Sort expression
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.

Comments

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);
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.