C# Program to order array elements in descending order


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

Updated on: 23-Jun-2020

143 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements