📜  LINQ ThenBy运算符

📅  最后修改于: 2021-01-06 05:15:22             🧑  作者: Mango

LINQ ThenBy运算符

ThenBy运算符用于对多个字段进行排序,默认情况下,ThenBy运算符将按升序对项目集合进行排序。通常,在LINQ中,将ThenBy运算符与OrderBy运算符一起使用以对列表/集合中的多个字段实施排序。

如果我们希望在LINQ上进行排序的条件不止一个,那么我们可以使用ThenBy子句和OrderBy子句。在LINQ中,OrderBy是主要的排序运算符,而ThenBy是次要的运算符。

LINQ ThenBy运算符的语法

在LINQ中使用ThenBy运算符对多个字段实施排序的语法为:

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

在上面的语法中,我们使用“ Name ”对项目列表进行排序,并通过使用ThenBy条件对项目列表进行排序添加了另一个字段“ Roleid”。现在,我们将借助示例了解这一点。

LINQ ThenBy运算符的示例

这是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
            List Objstudent = 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; }
                }
}

在上面的示例中,我们使用Name,RoleNumber Id多个字段对“ ObjStudent”列表项进行排序。

输出:

LINQ ThenBy排序运算符基于多个字段对项目列表进行排序的结果是: