Get Average Using 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
};
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.
double RatingAverage = ctx.Rates.Where(r => r.Id == Id).Average(r => r.Rating);
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()
});
This could also work if you don't want to calculate the average separately and rating is from another table
var query = (from u in db.Users
where rating.Id == Id
select new ViewModel
{
UserId = rating.UserId
Rating = (from c in db.Comments where c.fkUserId.Equals(u.Id) select c.StarRating).Average()
}).ToList();
return query;
It will return rating average.
Note: Use Rating as nullable double type i.e. double? Rating
精彩评论