C# .Sort()
Published Feb 5, 2023
Contribute to Docs
The .Sort() array method arranges the elements of an array in ascending or alphabetical order.
Syntax
Array.Sort(myArray);
.Sort() is a static method of the Array object. It takes one parameter, myArray, a one-dimensional zero-based array.
Example
The following example initializes the letters array with strings, then uses the .Sort() method to arrange the strings alphabetically. Finally, a foreach loop passes each element of the sorted array to the Console.Write() method to be printed:
using System;public class Example{public static void Main(string[] args){string[] letters = {"M", "Y", "E", "T", "P"};Array.Sort(letters);foreach (string letter in letters){System.Console.Write(letter + " ");}}}
This example results in the following output:
E M P T Y
Codebyte Example
The following example is runnable and returns the numbers in the numbers array in ascending order:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C# on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.
- Beginner Friendly.15 hours