標籤:result sele 城市 字串 style student 邏輯 into 方法
group 子句返回一個 IGrouping<TKey,TElement> 對象序列,這些對象包含零個或更多與該組的索引值匹配的項。 例如,可以按照每個字串中的第一個字母對字串序列進行分組。 在這種情況下,第一個字母就是鍵,類型為 char,並且儲存在每個 IGrouping<TKey,TElement> 對象的 Key 屬性中。 編譯器可推斷鍵的類型。
可以用 group 子句結束查詢運算式,如以下樣本所示:
// Query variable is an IEnumerable<IGrouping<char, Student>>var studentQuery1 = from student in students group student by student.Last[0];
如果要對每個組執行附加查詢操作,可使用內容關鍵字 into 指定一個臨時標識符。 使用 into 時,必須繼續編寫該查詢,並最終使用一個select 語句或另一個 group 子句結束該查詢,如以下代碼摘錄所示:
// Group students by the first letter of their last name// Query variable is an IEnumerable<IGrouping<char, Student>>var studentQuery2 = from student in students group student by student.Last[0] into g orderby g.Key select g;
枚舉查詢分組的結果
由於 group 查詢產生的 IGrouping<TKey,TElement> 對象實質上是一個由列表組成的列表,因此必須使用嵌套的 foreach 迴圈來訪問每一組中的各個項。 外部迴圈用於逐一查看組鍵,內部迴圈用於逐一查看組本身包含的每個項。 組可能具有鍵,但沒有元素。 下面的 foreach 迴圈執行上述程式碼範例中的查詢:
// Iterate group items with a nested foreach. This IGrouping encapsulates// a sequence of Student objects, and a Key of type char.// For convenience, var can also be used in the foreach statement.foreach (IGrouping<char, Student> studentGroup in studentQuery2){ Console.WriteLine(studentGroup.Key); // Explicit type for student could also be used here. foreach (var student in studentGroup) { Console.WriteLine(" {0}, {1}", student.Last, student.First); } }按複合鍵分組
希望按照多個鍵對元素進行分組時,可使用複合鍵。 使用匿名型別或命名類型來儲存鍵元素,建立複合鍵。 在下面的樣本中,假定已經使用名為 surname 和 city 的兩個成員聲明了類 Person。 group 子句會為每組姓氏和城市相同的人員建立一個單獨的組。
group person by new {name = person.surname, city = person.city};
如果必須將查詢變數傳遞給其他方法,請使用命名類型。 使用鍵的自動實作屬性建立一個特殊類,然後替代 Equals 和 GetHashCode 方法。 還可以使用結構,在此情況下,並不嚴格要求替代這些方法。 有關詳細資料,請參閱如何:使用自動實作屬性實現輕量類和如何:查詢分類樹中的重複檔案 (LINQ)。 後一個主題包含的程式碼範例示範了如何將複合鍵與命名類型結合使用。
樣本
此樣本示範在建立組之後,如何使用通過 into 實現的延續對這些組執行附加邏輯。 有關詳細資料,請參閱 into。 下面的樣本查詢每個組,僅選擇索引值為母音的元素。
class GroupClauseExample2{ static void Main() { // Create the data source. string[] words2 = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese", "elephant", "umbrella", "anteater" }; // Create the query. var wordGroups2 = from w in words2 group w by w[0] into grps where (grps.Key == ‘a‘ || grps.Key == ‘e‘ || grps.Key == ‘i‘ || grps.Key == ‘o‘ || grps.Key == ‘u‘) select grps; // Execute the query. foreach (var wordGroup in wordGroups2) { Console.WriteLine("Groups that start with a vowel: {0}", wordGroup.Key); foreach (var word in wordGroup) { Console.WriteLine(" {0}", word); } } // Keep the console window open in debug mode Console.WriteLine("Press any key to exit."); Console.ReadKey(); }}/* Output: Groups that start with a vowel: a abacus apple anteater Groups that start with a vowel: e elephant Groups that start with a vowel: u umbrella*/
C# group 子句