測試數據:
class Student { public string Name { get; set; } public int Score { get; set; } } List<Student> students = new List<Student>{ new Student {Name="Terry", Score=50}, new Student {Name="Tom", Score=85}, new Student {Name="Wade", Score=90}, new Student {Name="James", Score=70}, new Student {Name="Kobe", Score=90}, new Student {Name="AK", Score=90}, };
1.OrderBy
說明:在查詢表達式中,orderby子句可對集合按升序(ascending)或降序(descending)排序(默認的是升序)。可以指定多個排序的值,以便執行一個或多個次要排序操作。
對分數進行降序排序,然后再將分數相同的學生姓名進行升序排列(分數為主要排序,姓名為次要排序):
var query = from student in students orderby student.Score descending, student.Name select student; foreach (var student in query) { Console.WriteLine("{0}:{1}", student.Name, student.Score); //AK:90 //Kobe:90 //Wade:90 //Tom:85 //James:70 //Terry:50 }
2.Group By
(1)說明:group子句返回一個 IGrouping<TKey, TElement> 對象序列,這些對象包含零個或更多個與該組的鍵值匹配的項。 例如,可以按照每個字符串中的第一個字母對字符串序列進行分組。 在這種情況下,第一個字母是鍵且具有 char 類型,並且存儲在每個 IGrouping<TKey, TElement> 對象的Key屬性中。
按照學生分數分組:
var query = from student in students group student by student.Score; foreach (var studentGroup in query) { //studentGroup推斷為IGrouping<int,Student>類型 Console.WriteLine("{0}", studentGroup.Key); //50 //85 //90 //70 }
(2)說明:由於 group 查詢產生的 IGrouping<TKey, TElement> 對象實質上是列表的列表,因此必須使用嵌套的 foreach 循環來訪問每一組中的各個項。 外部循環用於循環訪問組鍵,內部循環用於循環訪問組本身中的每個項。組可能具有鍵,但沒有元素。如果您想要對每個組執行附加查詢操作,則可以使用 into 上下文關鍵字指定一個臨時標識符。 使用 into 時,必須繼續編寫該查詢,並最終用一個 select 語句或另一個 group 子句結束該查詢。
查詢每個分數組中的每個學生的信息:
var query = from student in students group student by student.Score into g select g; foreach (var studentGroup in query) { Console.WriteLine("分數組:{0}", studentGroup.Key); foreach (var student in studentGroup) { Console.Write("{0}:{1},", student.Name,student.Score); } Console.WriteLine(); //分組:50 //Terry:50, //分組:85 //Tom:85, //分組:90 //Wade:90,Kobe:90,AK:90, //分組:70 //James:70, }
(3)同樣的,group 子句可按照任何類型進行分組,如字符串、內置數值類型、用戶定義的命名類型或匿名類型。形式差不多,有需要可查閱其他資料