group
The igrouping<tkey,telement> clause returns a sequence of object objects that contain 0 or more items that match the key values of the group. For example, a sequence of strings can be grouped by the first letter in each string. In this case, the first letter is the key, the type is char, and is stored in the properties of each Igrouping<tkey,telement> object Key
. The compiler can infer the type of the key.
You can group
end a query expression with a clause, as shown in the following example:
// Query variable is an Ienumerable<igrouping<char, student>> var studentQuery1 = from the students group student by student. last[0];
If you want to perform additional query operations on each group, you can use the context keyword into to specify a temporary identifier. into
when used, you must continue writing the query and end select
the query with a statement or another group
clause, as shown in the following code excerpt:
// Group students by the first letter of their last name // Query variable is an Ienumerable<igrouping<char, student>> var studentQuery2 = from the students group student by student. last[0] into G by g.key select g;
Enumerate the results of a query grouping
Because group
the Igrouping<tkey,telement> object produced by a query is essentially a list of lists, nested foreach loops must be used to access individual items in each group. The outer loop is used to iterate through the group keys, and the inner loop is used to iterate through each item contained in the group itself. A group may have keys, but no elements. The following foreach
loop executes the query in the preceding code example:
//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 is used in the foreach statement.foreach(igrouping<Char, Student> StudentgroupinchStudentQuery2) {Console.WriteLine (Studentgroup.key); //Explicit type for student could also is used here. foreach(varStudentinchStudentgroup) {Console.WriteLine ("{0}, {1}", student. Last, student. First); } }
Group BY Composite Key
You can use a composite key when you want to group elements by multiple keys. Use anonymous or named types to store key elements and create composite keys. In the following example, it is assumed that the class has been surname
city
declared with two members named and Person
. group
clause creates a separate group for each group of people with the same last name and city.
New
If you must pass a query variable to another method, use a named type. Create a special class with the auto-implemented properties of the key, and then replace the Equals and GetHashCode methods. Structures can also be used, in which case it is not strictly required to override these methods. For more information, see How to: Implement Lightweight classes with auto-implemented properties and how to: query for duplicate files in a directory tree (LINQ). The latter topic contains code examples that demonstrate how to use composite keys with named types.
Example
This example shows how to use the continuations that are into
implemented to perform additional logic on these groups after the group is created. For more information, see into. The following example queries each group, selecting only the elements with the key values as vowels.
classgroupclauseexample2{Static voidMain () {//Create the data source. string[] Words2 = {"Blueberry","Chimpanzee","Abacus","Banana","Apple","Cheese","Elephant","Umbrella","anteater" }; //Create the query. varWORDGROUPS2 = fromWinchWORDS2 Group W by w[0] into GRPswhere(GRPs. Key = ='a'|| GRPs. Key = ='e'|| GRPs. Key = ='I'|| GRPs. Key = ='o'|| GRPs. Key = ='u') SelectGRPs; //Execute the query. foreach(varWordgroupinchwordGroups2) {Console.WriteLine ("Groups that start with a vowel: {0}", Wordgroup.key); foreach(varWordinchWordgroup) {Console.WriteLine ("{0}", Word); } } //Keep the console window open in debug modeConsole.WriteLine ("Press any key to exit."); Console.readkey (); }}/*output:groups that start with a vowel:a abacus Apple anteater Groups This start with a V Owel:e Elephant Groups that start with a vowel:u umbrella*/
C # Group clause