在计算平均值时是否可以使用Skip和Take?

时间:2017-02-12 07:16:22

标签: c# entity-framework linq

我正在尝试使用LINQ to Entities创建查询,以计算产品评级的平均值。在订购评级之前,我将每个产品的平均值预测为匿名对象。然后我想只取一部分结果。

查询如下:

var query = Items.GroupBy(review => review.Product)
            .Select(group => new
            {
                Product = group.Key,
                Rating = group.Average(review => review.Rating)
            })
            .OrderByDescending(pr => pr.Rating)
            .Skip(itemsToSkip)
            .Take(count)
            .ToList();

生成的查询如下所示:

{SELECT 
1 AS [C1], 
[GroupBy1].[K1] AS [ProductId], 
[GroupBy1].[K2] AS [TotalImages], 
[GroupBy1].[K3] AS [TotalVideos], 
[GroupBy1].[K4] AS [TotalAudioRecordings], 
[GroupBy1].[K5] AS [Name], 
[GroupBy1].[K6] AS [DiscountedPrice], 
[GroupBy1].[K7] AS [Status], 
[GroupBy1].[A1] AS [C2]
FROM ( SELECT 
    [Extent2].[ProductId] AS [K1], 
    [Extent2].[TotalImages] AS [K2], 
    [Extent2].[TotalVideos] AS [K3], 
    [Extent2].[TotalAudioRecordings] AS [K4], 
    [Extent2].[Name] AS [K5], 
    [Extent2].[DiscountedPrice] AS [K6], 
    [Extent2].[Status] AS [K7], 
    AVG([Extent1].[Rating]) AS [A1]
    FROM  [dbo].[ProductReviews] AS [Extent1]
    LEFT OUTER JOIN [dbo].[Products] AS [Extent2] ON [Extent1].[Product_ProductId] = [Extent2].[ProductId]
    GROUP BY [Extent2].[ProductId], [Extent2].[TotalImages], [Extent2].[TotalVideos], [Extent2].[TotalAudioRecordings], [Extent2].[Name], [Extent2].[DiscountedPrice], [Extent2].[Status]
)  AS [GroupBy1]}

查询不能跳过任何项目,也不能只取几个结果。而是返回数据库中每个产品的平均值计算。

我可以尝试使用SkipTake吗?如果是这样,我如何更正查询以获得所需的结果?我不希望从数据库中撤回所有数据。

1 个答案:

答案 0 :(得分:1)

我认为您可能需要在查询中再添加一个选择:

var query = Items.GroupBy(review => review.Product)
.Select(group => new
{
    Product = group.Key,
    Rating = group.Average(review => review.Rating)
})
.OrderByDescending(pr => pr.Rating)
.Select(x => new { Product = x.Product, Rating = x.Rating })
.Skip(itemsToSkip)
.Take(count)
.ToList();