LINQ to SQL find average of field?
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开发者_如何学JAVA of an object in my code?
(Pretty new, so let me know if any terminology is off, or if you need more info)
Thanks.
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();
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();
};
精彩评论