引導語:C#看起來與Java有著驚人的相似;它包括了諸如單一繼承、介面、與Java幾乎同樣的語法和編譯成中間程式碼再執行的過程。以下是小編整理的c#查詢關鍵字之group子句的使用,歡迎參考閱讀!
group 子句返回一個 IGrouping<(Of <(TKey, TElement>)>) 物件序列,這些物件包含零個或更多個與該組的鍵值匹配的項。例如,可以按照每個字串中的第一個字母對字串序列進行分組。在這種情況下,第一個字母是鍵且具有 char 型別,並且儲存在每個 IGrouping<(Of <(TKey, TElement>)>) 物件的 Key 屬性中。編譯器可推斷該鍵的型別。
可以用 group 子句結束查詢表示式,如下面的示例所示:
C#
// Query variable is an IEnumerable<IGrouping<char, Student>>
var studentQuery1 =
from student in students
group student by [0];
如果您想要對每個組執行附加查詢操作,則可以使用 into 上下文關鍵字指定一個臨時識別符號。使用 into 時,必須繼續編寫該查詢,並最終用一個 select 語句或另一個 group 子句結束該查詢,如下面的程式碼摘錄所示:
C#
// 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 [0] into g
orderby
select g;
本主題中的“示例”部分中提供了使用含有和不含 into 的 group 的更完整示例。
列舉組查詢的結果
由於 group 查詢產生的 IGrouping<(Of <(TKey, TElement>)>) 物件實質上是列表的列表,因此必須使用巢狀的 foreach 迴圈來訪問每一組中的各個項。外部迴圈用於迴圈訪問組鍵,內部迴圈用於迴圈訪問組本身中的每個項。組可能具有鍵,但沒有元素。以下是執行上述程式碼示例中的查詢的 foreach 迴圈:
C#
// 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)
{
eLine();
// Explicit type for student could also be used here.
foreach (var student in studentGroup)
{
eLine(" {0}, {1}", , t);
}
}
鍵型別
組鍵可以是任何型別,如字串、內建數值型別、使用者定義的命名型別或匿名型別。
按字串進行分組
上述程式碼示例使用的是 char。可以很容易地改為指定字串鍵,如完整的姓氏:
C#
// Same as previous example except we use the entire last name as a key.
// Query variable is an IEnumerable<IGrouping<string, Student>>
var studentQuery3 =
from student in students
group student by ;
按布林進行分組
下面的示例演示使用布林值作為鍵將結果劃分成兩個組。請注意,該值是由 group 子句中的子表示式產生的。
C#
class GroupSample1
{
// The element type of the data source.
public class Student
{
public string First { get; set; }
public string Last { get; set; }
public int ID { get; set; }
public List<int> Scores;
}
public static List<Student> GetStudents()
{
// Use a collection initializer to create the data source. Note that each element
// in the list contains an inner sequence of scores.
List<Student> students = new List<Student>
{
new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 72, 81, 60}},
new Student {First="Claire", Last="O'Donnell", ID=112, Scores= new List<int> {75, 84, 91, 39}},
new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {99, 89, 91, 95}},
new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {72, 81, 65, 84}},
new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {97, 89, 85, 82}}
};
return students;
}
static void Main()
{
// Obtain the data source.
List<Student> students = GetStudents();
// Group by true or false.
// Query variable is an IEnumerable<IGrouping<bool, Student>>
var booleanGroupQuery =
from student in students
group student by age() >= 80; //pass or fail!
// Execute the query and access items in each group
foreach (var studentGroup in booleanGroupQuery)
{
eLine( == true ? "High averages" : "Low averages");
foreach (var student in studentGroup)
{
eLine(" {0}, {1}:{2}", , t, age());
}
}
// Keep the console window open in debug mode.
eLine("Press any key to exit.");
Key();
}
}
/* Output:
Low averages
Omelchenko, Svetlana:77.5
O'Donnell, Claire:72.25
Garcia, Cesar:75.5
High averages
Mortensen, Sven:93.5
Garcia, Debra:88.25
*/
按數值範圍進行分組
下一個示例使用表示式建立表示百分比範圍的數值組鍵。請注意,該示例使用 let 作為方法呼叫結果的方便儲存位置,從而無需在 group 子句中呼叫該方法兩次。另請注意,在 group 子句中,為了避免發生“被零除”異常,程式碼進行了相應檢查以確保學生的平均成績不為零。有關如何在查詢表示式中安全使用方法的更多資訊,請參見如何:在查詢表示式中處理異常(C# 程式設計指南)。
C#
class GroupSample2
{
// The element type of the data source.
public class Student
{
public string First { get; set; }
public string Last { get; set; }
public int ID { get; set; }
public List<int> Scores;
}
public static List<Student> GetStudents()
{
// Use a collection initializer to create the data source. Note that each element
// in the list contains an inner sequence of scores.
List<Student> students = new List<Student>
{
new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 72, 81, 60}},
new Student {First="Claire", Last="O'Donnell", ID=112, Scores= new List<int> {75, 84, 91, 39}},
new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {99, 89, 91, 95}},
new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {72, 81, 65, 84}},
new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {97, 89, 85, 82}}
};
return students;
}
// This method groups students into percentile ranges based on their
// grade average. The Average method returns a double, so to produce a whole
// number it is necessary to cast to int before dividing by 10.
static void Main()
{
// Obtain the data source.
List<Student> students = GetStudents();
// Write the query.
var studentQuery =
from student in students
let avg = (int)age()
group student by (avg == 0 ? 0 : avg / 10) into g
orderby
select g;
// Execute the query.
foreach (var studentGroup in studentQuery)
{
int temp = * 10;
eLine("Students with an average between {0} and {1}", temp, temp + 10);
foreach (var student in studentGroup)
{
eLine(" {0}, {1}:{2}", , t, age());
}
}
// Keep the console window open in debug mode.
eLine("Press any key to exit.");
Key();
}
}
/* Output:
Students with an average between 70 and 80
Omelchenko, Svetlana:77.5
O'Donnell, Claire:72.25
Garcia, Cesar:75.5
Students with an average between 80 and 90
Garcia, Debra:88.25
Students with an average between 90 and 100
Mortensen, Sven:93.5
*/
按複合鍵進行分組
當您想要按照多個鍵對元素進行分組時,可使用複合鍵。通過使用匿名型別或命名型別來儲存鍵元素,可以建立複合鍵。在下面的示例中,假定已經使用名為 surname 和 city 的兩個成員聲明瞭類 Person。group 子句使得為每組具有相同姓氏和相同城市的人員建立一個單獨的組。
複製程式碼
group person by new {name = ame, city = };
如果必須將查詢變數傳遞給其他方法,請使用命名型別。使用自動實現的屬性作為鍵來建立一個特殊類,然後重寫 Equals 和 GetHashCode 方法。還可以使用結構;在此情況下,並不絕對需要重寫這些方法。有關更多資訊,請參見如何:使用自動實現的'屬性實現輕量類(C# 程式設計指南)和如何:在目錄樹中查詢重複檔案 (LINQ)。後一個主題包含一個程式碼示例,該示例演示如何將複合鍵與命名型別結合使用。
示例
下面的示例演示在沒有向組應用附加查詢邏輯時將源資料排序放入不同組中的標準模式。這稱為不帶延續的分組。字串陣列中的元素按照它們的第一個字母進行分組。查詢結果是一個 IGrouping<(Of <(TKey, TElement>)>) 型別,其中包含一個 char 型別的公共 Key 屬性以及一個包含分組中每個項的 IEnumerable<(Of <(T>)>) 集合。
group 子句的結果是序列的序列。因此,若要訪問所返回的每個組中的單個元素,請在迴圈訪問組鍵的迴圈內使用巢狀的 foreach 迴圈,如下面的示例所示。
C#
class GroupExample1
{
static void Main()
{
// Create a data source.
string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" };
// Create the query.
var wordGroups =
from w in words
group w by w[0];
// Execute the query.
foreach (var wordGroup in wordGroups)
{
eLine("Words that start with the letter '{0}':", );
foreach (var word in wordGroup)
{
eLine(word);
}
}
// Keep the console window open in debug mode
eLine("Press any key to exit.");
Key();
}
}
/* Output:
Words that start with the letter 'b':
blueberry
banana
Words that start with the letter 'c':
chimpanzee
cheese
Words that start with the letter 'a':
abacus
apple
*/
此示例演示在建立組之後,如何使用通過 into 實現的延續對這些組執行附加邏輯。有關更多資訊,請參見 into(C# 參考)。下面的示例查詢每個組以僅選擇那些鍵值為母音的元素。
C#
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 ( == 'a' || == 'e' || == 'i'
|| == 'o' || == 'u')
select grps;
// Execute the query.
foreach (var wordGroup in wordGroups2)
{
eLine("Groups that start with a vowel: {0}", );
foreach (var word in wordGroup)
{
eLine(" {0}", word);
}
}
// Keep the console window open in debug mode
eLine("Press any key to exit.");
Key();
}
}
/* 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
*/
備註
編譯時,group 子句被轉換為對 GroupBy 方法的呼叫。