ThenBy和ThenByDescending擴展方法用于對多個字段排序。
OrderBy ()方法根據(jù)指定的字段按升序?qū)线M行排序。在 OrderBy 之后使用 ThenBy ()方法按升序?qū)α硪粋€字段上的集合進行排序。Linq 首先根據(jù) OrderBy 方法指定的主字段對集合進行排序,然后根據(jù) ThenBy 方法指定的輔助字段按升序再次對結(jié)果集合進行排序。
以相同的方式,使用ThenByDescending方法以降序應(yīng)用二次排序。
下面的示例演示如何使用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。因此,現(xiàn)在,thenByResult排序后將包含以下元素:
StudentName: Bill, Age: 25 StudentName: John, Age: 18 StudentName: Ram, Age: 18 StudentName: Ram, Age: 20 StudentName: Ron, Age: 19 StudentName: Steve, Age: 15
現(xiàn)在 bydescresult 將包含以下元素。請注意,年齡為20歲的 Ram 比年齡為18歲的 Ram 更早出現(xiàn),因為它使用了 ThenByDescending 。
StudentName: Bill, Age: 25 StudentName: John, Age: 18 StudentName: Ram, Age: 20 StudentName: Ram, Age: 18 StudentName: Ron, Age: 19 StudentName: Steve, Age: 15
您可以在VB.Net中以相同的方式使用ThenBy和ThenByDescending方法,如下所示:
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)
默認(rèn)情況下,OrderBy和ThenBy對集合進行升序排序。
thenBy或ThenByDescending用于方法語法中的第二級排序。
thenByDescending方法在另一個字段上按降序?qū)线M行排序。
ThenBy或ThenByDescending在查詢語法中不適用。
通過使用逗號分隔字段,在查詢語法中應(yīng)用二級排序。
接下來了解有關(guān)分組運算符的信息。