This code sample shows you how to sort a string array in descending order. Since there is no method for sorting an array in descending order, I have done a small trick. No rocket science though!
class players { static void Main(string[] args) { string[] players = new string[] { "Pete Sampras", "John McEnroe", "Jimmy Connors", "Roy Emerson", "Rod Laver" };
//display elements of the array Console.WriteLine("Elements of String array"); foreach (string str in players) Console.Write(str + ", ");
Console.WriteLine();
//display elements of the array in sorted order Console.WriteLine("Elements of String array (sorted)"); Array.Sort(players);
foreach (string str in players) Console.Write(str + ", ");
Console.WriteLine(); Console.WriteLine("Elements of String array (in descending order)"); Array.Sort(players); Array.Reverse(players);
foreach (string str in players) Console.Write(str + ", ");
} }
The trick used was to sort an array and then reverse it (the array). Thus, we have an array sorted in the descending order.
OUTPUT:
Elements of String array Pete Sampras, John McEnroe, Jimmy Connors, Roy Emerson, Rod Laver, Elements of String array (sorted) Jimmy Connors, John McEnroe, Pete Sampras, Rod Laver, Roy Emerson, Elements of String array (in descending order) Roy Emerson, Rod Laver, Pete Sampras, John McEnroe, Jimmy Connors,
|
No responses found. Be the first to respond and make money from revenue sharing program.
|