按ID的Linq投影计数

时间:2018-11-23 09:08:05

标签: c# entity-framework linq

我是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;
    }

1 个答案:

答案 0 :(得分:1)

假设您的Customer类包含List<Order> Orders,而Order类包含字段Price

...
Orders = r.Orders.Count(),
AvgPrice = r.Orders.Average(o => o.Price)
...