当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C# Linq ThenByDescending()用法及代码示例


这里我们将使用Linq OrderByDescending() 和List 的ThenByDescending() 方法。这里 OrderBy() 方法用于在第一级对员工详细信息进行排序,然后使用 ThenByDescending() 方法在第二级对员工信息进行排序。

注意:OrderByDescending() 和 ThenByDescending() 方法用于按降序排序。

程序:

下面给出了演示 Linq ThenByDescending() 方法的源代码。给定的程序在 Microsoft Visual Studio 上编译并成功执行。

//C# program to demonstrate the Linq ThenByDescending() method.

using System;
using System.Linq;
using System.Collections.Generic;

public class Employee
{
    int ID;
    string Name;
    int Salary;
    string Department;

    public override string ToString()
    {
        return ID + " " + Name + " " + Salary + " " + Department;
    }

    static void Main(string[] args)
    {
        List<Employee> employees = new List<Employee>()
        {
             new Employee {ID=101,   Name="Amit  "    , Salary=4000,Department="ABC"},
             new Employee {ID=102,   Name="Amit  "    , Salary=3000,Department="XYZ"},
             new Employee {ID=103,   Name="Salman"    , Salary=3000,Department="ABC"},
             new Employee {ID=104,   Name="Ram   "    , Salary=2000,Department="XYZ"},
             new Employee {ID=105,   Name="Shyam "    , Salary=7000,Department="ABC"},
             new Employee {ID=106,   Name="Kishor"    , Salary=5000,Department="XYZ"},
        };


        var result = employees.OrderByDescending(name => name.Name).ThenByDescending(sal=>sal.Salary);


        Console.WriteLine("ID  Name  Salary  Department");
        Console.WriteLine("============================");
        foreach (Employee emp in result)
        {
            Console.WriteLine(emp.ToString());
        }
        Console.WriteLine("============================");
    }
}

输出:

ID  Name  Salary  Department
============================
105 Shyam  7000 ABC
103 Salman 3000 ABC
104 Ram    2000 XYZ
106 Kishor 5000 XYZ
101 Amit   4000 ABC
102 Amit   3000 XYZ
============================
Press any key to continue . . .

说明:

在上面的程序中,我们创建了一个Employee类,其中包含数据成员ID、Name、Salary和Department,Employee类还包含静态方法Main()。 Main() 方法是程序的入口点。

在 Main() 方法中,我们使用 List 集合创建了员工列表。然后我们使用 OrderByDescending() 和 ThenByDescending() 方法按降序对员工列表进行排序。 OrderByDescending() 方法用于第一级排序,ThenByDescending() 用于不同字段的下一级排序。




相关用法


注:本文由纯净天空筛选整理自 C# program to demonstrate the example of Linq ThenByDescending() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。