Group by (keyword)
From The Oxygene Language Wiki
This is a Language topic
Feel free to add your notes to this topic below.
Sometimes it is useful to partition data into subsets and process them individually. For example, we might want to print a list of customers grouped by city.
Query expressions do provide an option for this, with the group by clause:
var list := from c in MyCustomers group by c.City; for each group in list do begin Console.WriteLine('City: '+ group.Key); for each cust in group do Console.WriteLine(cust.Name); end;
The group by does not return a sequence of customers – it returns a sequence of groupings instead. Each of these groupings represents one partition of data – customers living in London, customers living in Des Moines, and so on.
Every grouping contains a Key – the original value grouped by, in this case the city name – and also is a sequence of customers itself. Therefore we can loop across all the groupings returned in list to get the cities, and then loop over each of the groups, to enumerate the customers of the respective city.
The expression supplied to the group by clause, incidentally, can be any arbitrary expression – the group by logic will compare for equality to decide the grouping.
group by can be followed by the into keyword to give a name to the new sequence of grouping, so it can be referenced further down in the query, such as:
var list := from c in MyCustomers group by c.City into g ...;
See Also
Area: Oxygene Language
Compiler version: Oxygene 5
Language Glossary — Keywords — Types — FAQ — How To