LINQ thenby降序运算符

本文概述

  • LINQ ThenByDescending运算符的语法
  • LINQ ThenByDescending运算符的示例
在LINQ中, ThenByDescending运算符用于对列表/集合中的多个字段进行排序, 默认情况下, ThenByDescending运算符将按降序对项目列表进行排序。在LINQ中, 我们将ThenByDescending运算符与OrderBy运算符一起使用。
在LINQ中, 那么ThenByDescending运算符用于将第二个排序条件指定为降序, 而OrderBy运算符用于指定主排序的条件。
LINQ ThenByDescending运算符的语法 使用LINQ ThenByDescending运算符与OrderBy运算符一起实现对项目的列表/集合进行排序的语法。
C#代码
var studentname = Objstudent.OrderBy(x => x.Name).ThenByDescending(x => x.RoleId);

【LINQ thenby降序运算符】从上面的示例可以看出, 我们首先使用OrderBy运算符定义了排序条件, 然后使用了ThenByDescending运算符定义了第二条件。我们正在使用” 名称” 对项目列表进行排序, 并使用ThenByDescending运算符添加了另一个字段” RoleId” 。
我们将借助示例进行查看。
LINQ ThenByDescending运算符的示例 这是LINQ ThenByDescending运算符的示例, 用于基于多个字段对项目的列表/集合进行排序:
using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp1{class Program{static void Main(string[] args){//Create object ObjStudent of the Student class having the list of the student informationList< Student> Objstudent = new List< Student> (){new Student() { RoleId=1, Name = "Suresh Dasari", Gender = "Male", Subjects = new List< string> { "Mathematics", "Physics" } }, new Student() { RoleId=2, Name = "Rohini Alavala", Gender = "Female", Subjects = new List< string> { "Entomology", "Botany" } }, new Student() { RoleId=3, Name = "Praveen Kumar", Gender = "Male", Subjects = new List< string> { "Computers", "Operating System", "Java" } }, new Student() { RoleId=4, Name = "Sateesh Chandra", Gender = "Male", Subjects = new List< string> { "English", "Social Studies", "Chemistry" } }, new Student() { RoleId=5, Name = "Madhav Sai", Gender = "Male", Subjects = new List< string> { "Accounting", "Charted" } }}; //ThenByDescending() operator is used to sort the information of the student in the descending formvar studentname = Objstudent.OrderBy(x => x.Name).ThenByDescending(x => x.RoleId); foreach (var student in studentname){Console.WriteLine("Name={0} StudentId={1}", student.Name, student.RoleId); }Console.ReadLine(); }}//create a student classclass Student{public int RoleId { get; set; }public string Name { get; set; }public string Gender { get; set; }public List< string> Subjects { get; set; }}}

在上面的示例中, 我们通过使用多个字段Name, RoleId对项目的” ObjStudent” 列表进行排序。
输出
LINQ thenby降序运算符

文章图片

    推荐阅读