Linq如何分组2场?
(from i in info
group i by i.OrderId into g
select new { orderId = g.Key, infos = g });
不仅按订单ID排序,还有两个字段,如...
group by i.orderId And i.City
这会怎么做?
答案 0 :(得分:4)
我相信你想要这样的东西:
var result = from i in info
group i by new { OrderId = i.OrderId, City = i.City } into g
select new { OrderId = g.Key, Infos = g };
将密钥创建为匿名类型只允许LINQ对匿名类型的所有字段使用默认的相等比较器,这在大多数情况下都可以完成。
答案 1 :(得分:3)
作为Noldorin答案的后续内容,您可以在匿名类型的字段名称与您设置的字段匹配时省略它们。
示例:
var result = from i in info
group i by new { i.OrderId, i.City } into g
select new { OrderId = g.Key, Infos = g };
答案 2 :(得分:2)
Noldorin和Josh Einstein的答案的另一个后续行动...... OrderID将采用整个密钥......在这种情况下,它是一个具有两个属性OrderID和City的新对象。如果您的最终结果集需要OrderID为OrderID,那么您需要执行以下操作:
var result = from i in info
group i by new { i.OrderId, i.City } into g
select new { OrderId = g.Key.OrderId, Infos = g };