Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Average Using LINQ

Tags:

c#

linq

Hoping someone can help me with the LINQ syntax to calculate an average. For example, I have the following LINQ query:

var rates = from rating in ctx.Rates               where rating.Id == Id               select new              {                    UserId = rating.UserId,                   Rating = rating.Rating               };   

If 10 records are returned, I need to calculate average on the Rating field. It is defined as as a Double in my DB. I am using LINQ to EF. So I would be assigning the UserId, MiscId, and the Rating would be the average on the records returned. I am passing one object back to the client code.

like image 714
obautista Avatar asked Jan 04 '11 04:01

obautista


People also ask

How to calculate average using LINQ?

In LINQ, you can find the average of the given sequence by using the Average method. This method returns the average of the elements present in the given sequence or collection. It returns nullable, non-nullable decimal, double, floats, int, etc. values.

How do you find the average in C#?

To find the average of integers in C#, use the Queryable Average() method. Let's say the following is our integer array. var arr = new int[] { 10, 17, 25, 30, 40, 55, 60, 70 }; Now, use the Average() method to get the average of the elements.

What is Linq in C# with example?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.


1 Answers

double RatingAverage = ctx.Rates.Where(r => r.Id == Id).Average(r => r.Rating); 
like image 164
Adam Rackis Avatar answered Sep 27 '22 21:09

Adam Rackis