使用 LINQ 获取平均值 [英] Get Average Using LINQ

查看:37
本文介绍了使用 LINQ 获取平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望有人可以帮助我使用 LINQ 语法来计算平均值.例如,我有以下 LINQ 查询:

Hoping someone can help me with the LINQ syntax to calculate an average. For example, I have the following LINQ query:

var rates = from rating in ctx.Rates  
            where rating.Id == Id  
            select new 
            {   
                UserId = rating.UserId,  
                Rating = rating.Rating  
            };  

如果返回 10 条记录,我需要计算 Rating 字段的平均值.它在我的数据库中被定义为 Double .我正在使用 LINQ to EF.因此,我将分配 UserId、MiscId,而 Rating 将是返回记录的平均值.我将一个对象传递回客户端代码.

If 10 records are returned, I need to calculate average on the Rating field. It is defined as as a Double in my DB. I am using LINQ to EF. So I would be assigning the UserId, MiscId, and the Rating would be the average on the records returned. I am passing one object back to the client code.

推荐答案

您是否正在寻找每个用户 ID 的平均评分?如果是这样,那么您需要同时使用 GroupBy平均值.

Are you looking for an average rating per user id? If so, then you need to use both GroupBy and Average.

var rates = ctx.Rates
               .Where( r => r.Id == Id )
               .GroupBy( g => g.UserId, r => r.Rating )
               .Select( g => new
                {
                   UserId = g.Key,
                   Rating = g.Average()
                }); 

这篇关于使用 LINQ 获取平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆