Sorting a String in C#

CsharpProgrammingServer Side Programming

Firstly, set a string array.

string[] values = { "tim", "amit", "tom", "jack", "saurav"};

Use the Sort() method to sort.

Array.Sort(values);

Let us see the complete code −

Example

 Live Demo

using System;
public class Program {
   public static void Main() {
      string[] values = { "tim", "amit", "tom", "jack", "saurav"};

      foreach (string value in values) {
         Console.Write(value);
         Console.Write(' ');
      }

      // sorting
      Array.Sort(values);
      Console.WriteLine("\nSorted...");
      foreach (string value in values) {
         Console.Write(value);
         Console.Write(' ');
      }
      Console.WriteLine();
   }
}

Output

tim amit tom jack saurav
Sorted...
amit jack saurav tim tom
raja
Published on 21-Aug-2018 08:12:34
Advertisements