📅  最后修改于: 2021-01-06 05:16:18             🧑  作者: Mango
在LINQ中, ThenByDescending运算符用于对列表/集合中的多个字段进行排序,默认情况下,ThenByDescending运算符将按降序对项目列表进行排序。在LINQ中,我们将ThenByDescending运算符与OrderBy运算符符一起使用。
在LINQ中,那么ThenByDescending运算符用于将第二个排序条件指定为降序,而OrderBy运算符用于指定主排序的条件。
使用LINQ ThenByDescending运算符与OrderBy运算符一起实现对项目的列表/集合进行排序的语法。
C#代码
var studentname = Objstudent.OrderBy(x => x.Name).ThenByDescending(x => x.RoleId);
从上面的示例中可以看出,我们首先使用OrderBy运算符定义了排序条件,然后使用ThenByDescending运算符定义了第二条件。我们使用“ Name ”对项目列表进行排序,并使用ThenByDescending运算符添加了另一个字段“ RoleId ”。
我们将借助示例进行查看。
这是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; }
}
}
在上面的示例中,我们通过使用多个字段Name,RoleId来对项目的“ ObjStudent ”列表进行排序。
输出: