-2

Well, I have a string array:

String array[] = new String[5];

array[0]="abc";
array[1]="aab";
array[2]="aaacb   sf";
array[3]="  ab";
array[4]="hello";

How do I order ascending and descending?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user647336
  • 75
  • 1
  • 2
  • 4

3 Answers3

14

Using LINQ, you could do:

array = array.OrderBy(d => d).ToArray();

to sort ascending

And

array = array.OrderByDescending(d => d).ToArray();

to sort descending

Remember to add using System.Linq;.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John Gathogo
  • 4,495
  • 3
  • 32
  • 48
2

Here is a sample: The "Array.Sort" function does this for you:

char[] array = { 'z', 'a', 'b' }; // Input array.
Array.Sort<char>(array); // Sort array.
foreach (var c in array)
    Console.WriteLine(c);

Look at dotnetPearls.

The LINQ functions ordering the array ascending and descending is also very well described with an sample.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Meister Schnitzel
  • 304
  • 2
  • 4
  • 11
1

You can use ORDERBY from LINQ to sort any collection (in .NET).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Piotr Auguscik
  • 3,651
  • 1
  • 22
  • 30