分组操作
分组是指将数据放入组中的操作,以便每个组中的元素共享一个公共属性。
GroupBy
分享共享公共属性的元素。
方法语法
// 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") }
查询语法
// 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
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") }
// }
查询语法
// Not applicable.