我正在尝试使用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吗?如果是这样,我如何更正查询以获得所需的结果?最好不要从数据库中拉回所有数据。

最佳答案

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

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();

关于c# - 在计算平均值时是否可以使用“跳过并取”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42185116/

10-15 21:12