2011-08-17 45 views
0

我正在構建一個基本博客模塊,允許用戶對博客文章進行評分。從變量中的數據計算平均值

評級通過ajax擴展提交,並作爲INT值保存在數據表中。

當我使用變量調用頁面上的評分時,我想計算總體平均評分。

任何人都可以告訴我如何去做這件事嗎?

這裏是我的代碼:

var rating = from x in db.DT_Control_BlogRatings 
         where x.Blog_ID == int.Parse(codesnippets.Decrypt(Request["blg"].ToString(), true)) 
         select new 
         { 
          x.RatingNo, 
          x.RatingID, 
         }; 

      string usercount = rating.Count().ToString(); 

      LB_UserRating.Text = "Currently rated " + usercount + " times"; 

非常感謝!

回答

1
// Extract the blog id before the query, because this instruction can't be translated to SQL 
int blogId = int.Parse(codesnippets.Decrypt(Request["blg"].ToString(), true)); 

var ratings = from x in db.DT_Control_BlogRatings 
       where x.Blog_ID == blogId 
       select x.RatingNo; 
var avg = ratings.Average(); 
3

您是否檢出IEnumerable Average方法?

在你的情況下,你會使用rating.Average(r => r.RatingNo)

0

我會說給定的職位的所有評級的總和除以他們的數量會給你一個平均值。

所以你有多久給給定的帖子被評爲+ 它有多好的評分功能。

0

嘗試

double ratingAverage = rating.Average (r => r.RatingNo); 
0

我認爲你可以這樣做:

double avg = rating.Average(rat=>rat.RatingNo); 

但是給你的次數可能是更好於:

int usercount = rating.Count(); 
double avg = rating.Sum(rat=>rat.RatingNo)/usercount;