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#
using System;
using System.Linq;
using System.Collections.Generic;
class GFG{
static void Main( string [] args)
{
List< string > students = new List< string >(){ "akhil" , "amrutha" ,
"yeswanth" , "praveen" };
var result = students.OrderByDescending(n => n);
Console.Write( "Sorted list in Descending order:\n" );
foreach ( string student in result)
{
Console.Write(student + " " );
}
}
}
|
OutputSorted list in Descending order:
yeswanth praveen amrutha akhil