c# - Finding Average of value based on count of rows in LINQ -


i have restaurant review application has separate restaurant , reviews table. have built mvc webapi has method passes restaurant object based on id of restaurant.

as part of object returned add average rating value, based on sum of rating values entered on reviews table divided restaurant id total count of reviews entered restaurant id.

it great if value in 1 decimal place format.

i able average value(no decimal places) reviews table using following code

var sum = (from in db.reviews            a.reviewsrestaurantid.equals(id)            select a.reviewsrating).sum();  var count = (from in db.reviews              a.reviewsrestaurantid.equals(id)              select a.reviewsrating).count();  decimal average = sum / count; 

i not sure how can add value query used return restaurant id method (pls see below). can please in adding custom average rating value method below or there way join on reviews table , calculate value more efficiently?

public iqueryable<restaurant> getrestaurantbyid(int id) {    var query = in db.restaurants               a.restaurantid.equals(id)               select a;    return query;  } 

for starters, can pare down code + traffic server. since mentioned tables, rows, , db, guess going sql server.

start getting of stuff care server, i.e.

var reviews = (from x in db.reviews a.reviewsrestaurantid.equals(id) select x).tolist(); 

now don't have make 2 seperate trips server collect data care about. can run , 'average' query on data have in memory...

// assuming, sample ratings stored decimals.... // counting, summing, dividing, etc. decimal avg = (from x in reviews select x.rating).average(); 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

How to get multiresult with multicondition in Sql Server -