我有一张由人做出的订单表:
Orders
{
Guid PersonId,
int Priority,
Guid GoodId
}
优先级是一些整数。例如:
AlenId 1 CarId
DianaId 0 HouseId
AlenId 3 FoodId
DianaId 2 FlowerId
我想为每个人检索最高优先级的订单:
AlenId 1 CarId
DianaId 0 HouseId
在T-SQL中我将使用排名,如何在Linq-2-Sql中获得相同的结果?
提前谢谢!
答案 0 :(得分:2)
这样的事情:
var query = from order in context.Orders
orderby order.Priority
group order by order.PersonId into personOrders
select personOrders.First();
我相信应该有效,但我不知道它在分组后的排序方面有多么明确。这也有用,虽然它有点丑陋:
var query = from order in context.Orders
group order by order.PersonId into personOrders
select personOrders.OrderBy(order => order.Priority).First();
或者只使用点符号:
var query = context.Orders
.GroupBy(order => order.PersonId)
.Select(group => group.OrderBy(order => order.Priority)
.First());