views:

56

answers:

2

I have a ViewModel called EntityRating, one of whose properties is AverageRating.

When I instantiate a new object of my ViewModel (called EntityRating) type, how do I set the EntityRating.AverageRating based on the Rating field (in SQL Server) of the item in question?

I want to do something like this (which obviously doesn't work):

var er = new EntityRating()
        {
            AverageRating = _db.All<Ratings>(X => X.RatingID = rating.RatingID).Average(RatingField);
        };

Can I average the properties of an object in the database and assign it to the property of an object in my code?

(Pretty new, so let me know if any terminology is off, or if you need more info)

Thanks.

+3  A: 

LINQ has the .Average extension method, however, that only works on integers. So what you need to do is get an IEnumerable of the RatingField property on all your Rating objects in the database. This can be accomplished by using the .Select extension method of LINQ which Projects each element of a sequence into a new form.

int average = _db.Ratings.Where(x => x.RatingID == rating.RatingID).Select(x => x.RatingField).Average();
Baddie
Thanks. Was forgetting the .Select()
johnnycakes
There's also the Average overload that accepts a Func<Foo, int>, so given a collection of ratings, you could also call .Average(x => x.RatingField)
Joe Enos
+1  A: 

There's a LINQ function Average() seen here: http://msdn.microsoft.com/en-us/library/bb399409.aspx

var er = new EntityRating()
{
  AverageRating = _db.Where(X => X.RatingID == rating.RatingID)
    .Select( x => x.RatingField).Average();
};
TJB