使用 LINQ 以降序对学生姓名进行排序的 C# 程序
给定一个学生姓名列表,现在我们的任务是使用 LINQ 按降序对列表中给出的姓名进行排序,此任务可以使用 LINQ 的 OrderByDescending() 方法完成。此方法用于按降序对集合中的元素进行排序。在 LINQ 查询中使用此方法时,您不需要添加额外的条件来按降序对列表进行排序。
例子:
Input : [ "sai", "narendra", "Mohan", "sundar", "vasu" ]
Output : [ "vasu", "sundar", "sai", "narendra", "mohan" ]
Input : [ "akhil", "amrutha", "yeswanth", "praveen" ]
Output : [ "yeswanth", "praveen", "amrutha", "akhil" ]
方法
- Create and initialize a list of strudent names of type string. For example arr.
- Sorting the list(named arr) using OrderByDescending() method.
- Display the result using the foreach loop.
C#
var finalres = arr.OrderByDescending(n => n);
输出
// 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 students = new List(){ "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 + " ");
}
}
}