C# - Sort student names in descending order using LINQ

Learn, how to sort student names in descending order using Linq in C#? By Nidhi Last updated : April 01, 2023

Here, we will create a list of student names and then sort them in descending order using the OrderByDescending() method.

C# program to sort student names in descending order using LINQ

The source code to sort student names in descending order using Linq is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to sort student names in 
//descending order using Linq.

using System;
using System.Linq;
using System.Collections.Generic;

class Demo {
  static void Main(string[] args) {
    List <string> students = new List <string> () {
      "Rocky",
      "Mohan",
      "Roni",
      "Ayan",
      "Kalpna"
    };

    var result = students.OrderByDescending(str => str);

    Console.WriteLine("Sorted list in Descending order:");
    foreach(string stud in result) {
      Console.Write(stud + " ");
    }
    Console.WriteLine();
  }
}

Output

Sorted list in Descending order:
Roni Rocky Mohan Kalpna Ayan
Press any key to continue . . .

Explanation

In the above program, we created a Demo class that contains the Main() method to start the execution of the program. In the main() method we created the list of student names and then we sort them using the OrderByDescending() method using the below code.

var result = students.OrderByDescending(str => str);

Then we printed the filtered values on the console screen.

C# LINQ Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.