无涯教程-ThenByDescending运算符

78 阅读1分钟

在LINQ中,ThenByDescending运算符用于实现列表/集合中多个字段的排序,默认情况下,ThenByDescending运算符会对列表中的项进行降序排序。在LINQ中,我们使用ThenByDescending运算符和OrderBy运算符。

在LINQ中,ThenByDescending运算符用于指定第二个排序条件为降序条件,OrderBy运算符用于指定主排序条件。

LINQ ThenByDescending运算符的语法

使用LINQThenByDescending运算符与OrderBy运算符一起实现项目列表/集合排序的语法。

C#代码

  var studentname = Objstudent.OrderBy(x => x.Name).ThenByDescending(x => x.RoleId);

From the above example, it shows that we defined first the sorting condition wiith OrderBy Operator and second condition with ThenByDescending operator. We are sorting the list of items using "Name" and we added another field "RoleId" by using ThenByDescending Operator.

我们将借助示例来了解。

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 information List Objstudent = new List() { new Student() { RoleId=1, Name = "Suresh Dasari", Gender = "Male", Subjects = new List { "Mathematics","Physics" } }, new Student() { RoleId=2, Name = "Rohini Alavala", Gender = "Female", Subjects = new List { "Entomology", "Botany" } }, new Student() { RoleId=3, Name = "Praveen Kumar", Gender = "Male", Subjects = new List { "Computers","Operating System", "Java" } }, new Student() { RoleId=4, Name = "Sateesh Chandra", Gender = "Male", Subjects = new List { "English", "Social Studies", "Chemistry" } }, new Student() { RoleId=5, Name = "Madhav Sai", Gender = "Male", Subjects = new List { "Accounting", "Charted" } } }; //ThenByDescending() operator is used to sort the information of the student in the descending form var 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 class class Student { public int RoleId { get; set; } public string Name { get; set; } public string Gender { get; set; } public List Subjects { get; set; } } }

In the above example, we are sorting the "ObjStudent" list of items by using the multiple fields Name, RoleId.

输出:

LINQ ThenBy Descending Operator




参考链接

www.learnfk.com/linq/linq-t…