Open In App

C# Program to Sort Student Names in Descending Order using LINQ

Last Updated : 29 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list of student names, now our task is to sort the names given in the list in descending order using the LINQ, This task can be done using OrderByDescending() method of LINQ. This method is used to sort the elements in the collection in descending order. While using this method in the LINQ query you don’t need to add an extra condition to sort the list in descending order.

Example:

Input  : [ "sai", "narendra", "Mohan", "sundar", "vasu" ]
Output : [ "vasu", "sundar", "sai", "narendra", "mohan" ]

Input  : [ "akhil", "amrutha", "yeswanth", "praveen" ]
Output : [ "yeswanth", "praveen", "amrutha", "akhil" ]

Approach

  • Create and initialize a list of strudent names of type string. For example arr.
  • Sorting the list(named arr) using OrderByDescending() method.
var finalres = arr.OrderByDescending(n => n);
  • Display the result using the foreach loop.

C#




// C# program to sort student names in
// descending order using Linq.
using System;
using System.Linq;
using System.Collections.Generic;
 
class GFG{
     
static void Main(string[] args)
{
     
    // Creating and initializing list
    List<string> students = new List<string>(){ "akhil", "amrutha",
                                                "yeswanth", "praveen" };
                                                  
    // Sorting the student names in descending order
    var result = students.OrderByDescending(n => n);
     
    // Display the sorted list
    Console.Write("Sorted list in Descending order:\n");
    foreach (string student in result)
    {
        Console.Write(student + " ");
    }
}
}


Output

Sorted list in Descending order:
yeswanth praveen amrutha akhil 

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads