Copy below:
Gone through the problem an got the relevant answer also made blog on it so visit the blog post
Some of the important aspects covered are described breifly as follows.
To rate an Item for the first time by a user the following fields should be modified with the respective field values:
- item["RatingCount"]:
This field stores the number of users who have rated the item its value should be incremented.
- item["Ratings"]:
A field which stores the user ratings in CSV string format should add the new users rating like.
int NewRating = 4; //any desired number from 1 to 5.
item["Ratings"] += NewRating + ",";
- item["AverageRating"]:
This field stores the average of the ratings given by all the rated users. Simple weighted average calculation formulas can be implemented which is
float OldAverage = item["AverageRating"] == null ? 0 : float.Parse(item["AverageRating"].ToString());
int OldNumberOfRatings = item["RatingCount"] == null ? 0 : int.Parse(item["RatingCount"].ToString());
int NewNumberOfRatings = OldNumberOfRatings + 1;
float NewAverage = OldAverage + ( ( NewRating - OldAverage ) / NewNumberOfRatings);
//Or.
float NewAverage = ( ( OldAverage * OldNumberOfRatings ) + NewRating ) / NewNumberOfRatings;
item["AverageRating"] = NewAverage;
- item["RatedBy"]:
This field stores the user information in form of array of FieldUserValue which can be modified using following code
FieldUserValue[] ratedUsers = item["RatedBy"] as FieldUserValue[];
//where ratedUsers becomes an array of users who have already rated.
List<FieldUserValue> newUsersRated = new List<FieldUserValue>();
if (ratedUsers != null)
foreach (FieldUserValue ratedUser in ratedUsers)
newUsersRated.Add(ratedUser);
newUsersRated.Add(FieldUserValue.FromUser(user.LoginName));
item["RatedBy"] = newUsersRated;
To Rerate the item for a user who has already rated it before you need to first find the user index (say int userIndex) in the item["RatedBy"] field then change the following fields:
- item["Ratings"]:
Change the user rating in this CSV string by use of userIndex.
FieldUserValue[] ratedUsers = item["RatedBy"] as FieldUserValue[];
for (int i = 0; i < ratedUsers.Length; i++)
if (ratedUsers[i].LookupValue == user.Title)
int userIndex = i;
string[] userRatings = item["Ratings"].split(',');
int OldRating = int.Parse(userRatings[userIndex]);
int NewRating = 3; //any desired number from 1 to 5.
userRatings[userIndex] = NewRating.ToString();
string ratings = userRatings.Join(',', userRatings);
item["Ratings"] = ratings;
- item["AverageRating"]:
change the average value using formula
float OldAverage = item["AverageRating"];
int NumberOfRatings = item["RatingCount"];
float NewAverage = OldAverage + ( ( NewRating - OldRating ) / NumberOfRatings );
item["AverageRating"] = NewAverage;