In C #, since the LINQ query expression has been used, the programmer performs a series of filtering, sorting, filtering, grouping, querying, and other actions on the sequence or list that can be iterated. This article describes the Group keyword.
LINQ query expressions, which start with the FROM keyword and end with a select or group keyword, can insert where, by-order, join, let, or even additional from clauses.
The group clause returns a sequence of igrouping<tkey,telement> objects, note that it is an object sequence, not a single object. Because the igrouping<tkey,telement> generated by the group query is essentially a list of lists. Therefore, you must use a nested foreach loop to access the individual subkeys of each group. External loops can access each group's key, and internal loops can access the subkeys of each group.
The key for each group can be any type, such as a string, a user-defined object, or other.
You can group the series with the following code:
Non-sorted direct grouping
var from in cities Group by city. Name;
//grouping by key of each groupvarCitygroup = fromCityinchCities//The names of each city are grouped first, and the children of each group are the cities object instances after the Group keyword group City by city. Name//then assign the group to a variable GInto g//then it can be sorted by the key of G, G.key is the parameter after the keyword, that is, city. Name G.key//finally select the group SelectG
// Customize each subkey of group var from inch Cities
//Note that the parameter after the by keyword must be associated with a parameter after the group keyword, otherwise it cannot be grouped new{city. Name,city. peoplecount,someparam=" custom " by city. Name
you can use nested foreach loops to get each subkey. Each subkey is actually an object that follows the group keyword, such as city.
foreach(varThecitiesinchCitygroup) { //first get the key for each group, at the time of grouping, by the parameter city behind it. NameConsole.WriteLine ("key:{0} for each group", Thecities.key); //then loop again to get the children of each group, which is the parameter city object that follows group foreach(varCityinchthecities) {Console.WriteLine ("City name: {0}", City. Name); Console.WriteLine ("total number of people: {0}", City. Peoplecount); } }
Reading notes Analysis of Group keywords in C # LINQ query