C# Program to order array elements in descending order

CsharpProgrammingServer Side Programming

To orders elements in a sequence in descending order, use ThenBy() and OrderByDescending.

This is our string array.

string[] myStr = { "Keyboard", "Laptop", "Mouse", "Monitor" };

Now, use OrderByDescending to order element in Descending order. Inside that calculate the length of each string and use Lambda Expressions as well.

IEnumerable<string> res = myStr.AsQueryable().OrderByDescending(ch => ch.Length).ThenBy(ch => ch);

The following is the example discussed above.

Example

 Live Demo

using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      string[] myStr = { "Keyboard", "Laptop", "Mouse", "Monitor" };
      IEnumerable<string> res = myStr.AsQueryable().OrderByDescending(ch => ch.Length).ThenBy(ch => ch);
      foreach (string arr in res)
      Console.WriteLine(arr);
   }
}

Output

Keyboard
Monitor
Laptop
Mouse
raja
Published on 14-Sep-2018 16:00:41
Advertisements