个性化阅读
专注于IT技术分析

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);

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

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<Student> Objstudent = new List<Student>()
            {
                new Student() { RoleId=1, Name = "Ak", Gender = "Male", Subjects = new List<string> { "Mathematics", "Physics" } }, new Student() { RoleId=2, Name = "Shalu", Gender = "Female", Subjects = new List<string> { "Computers", "Botany" } }, new Student() { RoleId=3, Name = "Shubham", Gender = "Male", Subjects = new List<string> { "Economics", "Operating System", "Java" } }, new Student() { RoleId=4, Name = "Rohit", Gender = "Male", Subjects = new List<string> { "Accounting", "Social Studies", "Chemistry" } }, new Student() { RoleId=5, Name = "Shivani", Gender = "FeMale", Subjects = new List<string> { "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<string> Subjects { get; set; }
                }
}

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

输出

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

LINQ ThenBy运算符

赞(0)
未经允许不得转载:srcmini » LINQ ThenBy运算符

评论 抢沙发

评论前必须登录!