You would think this would be an easy thing to find with a quick Goole search, but it's not. In a web app I'm working on, I just wanted to implement a simple rating for accounts from 1 to 5 stars. I figured someone has done this before and searched away. I found very little so I figured I would post some code showing how this is done in case some other poor soul wants to create a 5 star rating using C#. So here you go, internet:

``````
public class Rating
{
public int Weight
{
get;
private set;
}

public int NumberOfReviews
{
get;
private set;
}

public Rating(int weight, int numberOfReviews)
{
Weight = weight;
NumberOfReviews = numberOfReviews;
}
}
``````
``````
public class Program
{
public static void Main()
{
var ratings = new List();
ratings.Add(new Rating(5, 252));
ratings.Add(new Rating(4, 124));
ratings.Add(new Rating(3, 40));
ratings.Add(new Rating(2, 29));
ratings.Add(new Rating(1, 33));
Console.WriteLine(CalculateRating(ratings));
}

private static decimal CalculateRating(List ratings)
{
double totalWeight = 0;
int totalReviews = 0;
foreach (var rating in ratings)
{
var weightByNumber = rating.Weight * rating.NumberOfReviews;
totalWeight += weightByNumber;
totalReviews += rating.NumberOfReviews;
}

return (decimal)Math.Round(totalWeight / totalReviews, 2);
}
}
``````

This should print out 4.12 as the rating.