Grouping refers to the operations of putting data into groups so that the elements in each group share a common attribute.
GroupBy
Groups elements that share a common attribute.
Method Syntax
// GroupBy
class Order
{
public string Customer { get; set; }
public string Description { get; set; }
}
...
var orders = new Order[]
{
new Order { Customer = "C1", Description = "O1" },
new Order { Customer = "C2", Description = "O2" },
new Order { Customer = "C3", Description = "O3" },
new Order { Customer = "C1", Description = "O4" },
new Order { Customer = "C1", Description = "O5" },
new Order { Customer = "C3", Description = "O6" },
};
var groups = orders.GroupBy(o => o.Customer);
// groups: { (Key="C1", Values="O1","O4","O5"), (Key="C2", Values="O2"), (Key="C3", Values="O3","O6") }
Query Syntax
// group … by
var groups = from o in orders
group o by o.Customer;
// groups: { (Key="C1", Values="O1","O4","O5"), (Key="C2", Values="O2"), (Key="C3", Values="O3","O6") }
ToLookup
Inserts elements into a one-to-many dictionary based on a key selector function.
Method Syntax
// ToLookUp
var ordersByCustomer = orders.ToLookup(o => o.Customer);
// ordersByCustomer = ILookUp<string, Order>
// {
// "C1" => { Order("01"), Order("04"), Order("05") },
// "C2" => { Order("02") },
// "C3" => { Order("03"), Order("06") }
// }
Query Syntax
// Not applicable.