LINQ 學習路程 -- 查詢操作 OrderBy & OrderByDescending


Sorting Operator Description
OrderBy 通過給定的字段進行升序 降序 排序
OrderByDescending 通過給定字段進行降序排序,僅在方法查詢中使用
ThenBy 第二級升序排序,僅在方法查詢中使用
ThenByDescending 第二級降序排序,僅在方法查詢中使用
Reverse 反轉集合,僅在方法查詢中使用
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 } 
};

var orderByResult = from s in studentList
                   orderby s.StudentName 
                   select s;

var orderByDescendingResult = from s in studentList
                   orderby s.StudentName descending
                   select s;

 

 

OrderBy擴展方法有兩個重載方法,第一個方法接受一個類型參數,你可以指定通過哪個字段進行排序

第二個方法接受一個實現IComparer的類型,用戶可以自定義排序

public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, 
                                                                 Func<TSource, TKey> keySelector);

public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, 
                                                                 Func<TSource, TKey> keySelector, 
                                                                 IComparer<TKey> comparer);
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 } 
};

var studentsInAscOrder = studentList.OrderBy(s => s.StudentName);

 

OrderByDescending

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

var studentsInDescOrder = studentList.OrderByDescending(s => s.StudentName);

 

 

多個排序

可以使用多個字段以逗號隔開進行排序,集合首先以第一個字段進行排序,如果第一個字段有相同的值,則根據第二個字段進行排序

 

注意:

LINQ包含五種排序操作:OrderBy、OrderByDescending、ThenBy、ThenByDescending、Reverse

查詢語言不支持OrderByDescending、ThenBy、ThenByDescending、Reverse,它僅支持Order By從句后面跟ascending、descending

查詢語法支持多字段排序,

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM