我是Linq Projection的新手。我只想知道如何按ID计数。我需要计算每个客户的订单和平均订单价格。
public IQueryable<TemporaryCustomerModel> GetCustomersWithOrdersCountAndAveragePrice()
{
var result = dataContext.Customers
.Include(u => u.Order)
.Select(r => new TemporaryCustomerModel()
{
Id = r.Id,
FullName = r.Name + ' ' + r.Surname,
Email = r.Email,
Birthdate = r.Birthdate,
Gender = r.Gender.GetName(),
Orders = ???, //Count orders for every customer
AvgPrice = ??? //Average order price
});
return result;
}
答案 0 :(得分:1)
假设您的Customer
类包含List<Order> Orders
,而Order
类包含字段Price
...
Orders = r.Orders.Count(),
AvgPrice = r.Orders.Average(o => o.Price)
...