阅读 347

LINQ 排序运算符 ThenBy和ThenByDescending

ThenBy和ThenByDescending扩展方法用于对多个字段排序。

OrderBy ()方法根据指定的字段按升序对集合进行排序。在 OrderBy 之后使用 ThenBy ()方法按升序对另一个字段上的集合进行排序。Linq 首先根据 OrderBy 方法指定的主字段对集合进行排序,然后根据 ThenBy 方法指定的辅助字段按升序再次对结果集合进行排序。

以相同的方式,使用ThenByDescending方法以降序应用二次排序。

下面的示例演示如何使用ThenBy和ThenByDescending方法进行第二级排序:

示例:ThenBy&ThenByDescending

IList<Student> studentList = new List<Student>() { 
    new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,
    new Student() { StudentID = 2, StudentName = "Steve",  Age = 15 } ,
    new Student() { StudentID = 3, StudentName = "Bill",  Age = 25 } ,
    new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
    new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 }, 
    new Student() { StudentID = 6, StudentName = "Ram" , Age = 18 }
};var thenByResult = studentList.OrderBy(s => s.StudentName).ThenBy(s => s.Age);var thenByDescResult = studentList.OrderBy(s => s.StudentName).ThenByDescending(s => s.Age);

如您在上面的示例中所见,我们首先按排序studentList集合StudentName,然后按排序Age。因此,现在,thenByResult排序后将包含以下元素:

StudentName: Bill, Age: 25StudentName: John, Age: 18StudentName: Ram, Age: 18StudentName: Ram, Age: 20StudentName: Ron, Age: 19StudentName: Steve, Age: 15

现在 bydescresult 将包含以下元素。请注意,年龄为20岁的 Ram 比年龄为18岁的 Ram 更早出现,因为它使用了 ThenByDescending 。

StudentName: Bill, Age: 25StudentName: John, Age: 18StudentName: Ram, Age: 20StudentName: Ram, Age: 18StudentName: Ron, Age: 19StudentName: Steve, Age: 15

您可以在VB.Net中以相同的方式使用ThenBy和ThenByDescending方法,如下所示:

示例:ThenBy&ThenByDescending VB.Net

Dim sortedResult = studentList.OrderBy(Function(s) s.StudentName)
                              .ThenBy(Function(s) s.Age)Dim sortedResult = studentList.OrderBy(Function(s) s.StudentName)                              .ThenByDescending(Function(s) s.Age)

要记住的要点

  1. 默认情况下,OrderBy和ThenBy对集合进行升序排序。

  2. thenBy或ThenByDescending用于方法语法中的第二级排序。

  3. thenByDescending方法在另一个字段上按降序对集合进行排序。

  4. ThenBy或ThenByDescending在查询语法中不适用。

  5. 通过使用逗号分隔字段,在查询语法中应用二级排序。

接下来了解有关分组运算符的信息。


文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐