ThenBy排序运算符用于实现对多个字段的排序,默认情况下,ThenBy运算符会对项目集合进行升序排序。通常,在LINQ中,ThenBy运算符与OrderBy运算符一起使用来实现对列表/集合中的多个字段的排序。
如果我们希望在LINQ中有多个排序条件,那么可以使用ThenBy子句和OrderBy子句。在LINQ中,OrderBy是主要排序运算符,ThenBy是次要运算符。
在LINQ中使用ThenBy运算符实现多个字段排序的语法为:
var studentname = Objstudent.OrderBy(x => x.Name).ThenBy(x => x.RoleId);
In the above Syntax, we are sorting the list of items using "Name," and we added another field "Roleid" by using the ThenBy condition to sort the list of items. Now, we will see this with the help of an example.
下面是LINQ ThenBy运算符的示例,用于对基于多个字段的项目列表/集合进行排序。
C#代码
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 an object Objstudent of the class Student, and create a list of the information of the student ListObjstudent = new List () { new Student() { RoleId=1, Name = "Ak", Gender = "Male", Subjects = new List { "Mathematics", "Physics" } }, new Student() { RoleId=2, Name = "Shalu", Gender = "Female", Subjects = new List { "Computers", "Botany" } }, new Student() { RoleId=3, Name = "Shubham", Gender = "Male", Subjects = new List { "Economics", "Operating System", "Java" } }, new Student() { RoleId=4, Name = "Rohit", Gender = "Male", Subjects = new List { "Accounting", "Social Studies", "Chemistry" } }, new Student() { RoleId=5, Name = "Shivani", Gender = "FeMale", Subjects = new List { "English", "Charterd" } } }; //ThenBy() operator is used here to sort the Information of the student in ascending form on the behalf of the RollNumber var studentname = Objstudent.OrderBy(x => x.Name).ThenBy(x => x.RoleNumber Id); //foreach loop is used to print the information foreach (var student in studentname) { Console.WriteLine("Name={0} studentid={1}", student.Name, student.Roleid); } Console.ReadLine(); } } class Student { public int RoleNumber Id { 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 item using the multiple fields Name, RoleNumber Id.
输出:
LINQ ThenBy排序运算符根据多个字段对项目列表进行排序的结果为:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)