Get Average Using LINQ
Are you looking for an average rating per user id? If so, then you need to use both GroupBy and Average.
var rates = ctx.Rates
.Where( r => r.Id == Id )
.GroupBy( g => g.UserId, r => r.Rating )
.Select( g => new
{
UserId = g.Key,
Rating = g.Average()
});
How can I get the average of a property in a list using LINQ?
Try something like that;
var avg = btnCountViewsList.Where(x => x.Month == 5).Select(x => x.Views).DefaultIfEmpty(0).Average();
Also I suggest you to use DefaultIfEmpty
for possible empty sets. Otherwise if btnCountViewsList
is empty, an exception is throwed.
How to use linq to calculate average from grouped data where value 0 using let
you need to average field 3 after the filter
let field3Average = dg.Where(g => g.field3 > 0.0).Average(g => g.field3)
Finding the max of average in linq
Using Linq "query syntax"
var best = from student in students
group student by student.Id into studentAverage
let average = studentAverage.Average (s => s.Marks)
orderby average descending
select new { id = studentAverage.Key, average };
// change projection to have only id or averageUsing Linq "method syntax"
var best =
students
.GroupBy (student => student.Id,
student => student.Marks,
(id, marks) => new { id, average = marks.Average () })
.OrderByDescending (studentAverage => studentAverage.average)
// add a projection (Select) here to have only id or average
.FirstOrDefault ();Maybe simpler alternative but more oriented toward getting only the Id
var best =
students
.ToLookup (s => s.Id, s => s.Marks)
.OrderByDescending (marksById => marksById.Average ())
.FirstOrDefault ();
// Key will contain the Id but Average must be calculated again
// var avg = best.Average();Using "classic" code (longer, but clearer steps)
var studentMarks = new Dictionary<int, List<double>> (students.Count);
foreach (var student in students)
{
int id = student.Id;
List<double> marks;
if (!studentMarks.TryGetValue (id, out marks))
{
marks = new List<double> ();
studentMarks.Add (id, marks);
}
marks.Add (student.Marks);
}
double? bestAverage = null;
int? idOfBest = null;
foreach (var idAndMarks in studentMarks)
{
var average = 0.0;
foreach (var mark in idAndMarks.Value)
{
average += mark;
}
average /= idAndMarks.Value.Count;
if (average > bestAverage)
{
bestAverage = average;
idOfBest = idAndMarks.Key;
}
}
Conditional average using linq from qrouped data returns nothing
It sounds like there are groups that don't have any items that satisfy the Where
condition. The Average
of an empty sequence of non-nullable values is not zero - it is an exception. For example, there are no items for Field1
as 6
that have Field3
greater than zero.
I notice in your "What I want" table you only have the values with Field1
as 3
- if this represents your real scenario, maybe filter the second table.
A possible fix is to project the values to be nullable:
let AverageField3 = dg.Where(g => g.Field3 > 0.0).Average(g => (int?)g.Field3)
this will give a null
value when there aren't any inputs. If you want zero:
let AverageField3 = dg.Where(g => g.Field3 > 0.0)
.Average(g => (int?)g.Field3)
.GetValueOrDefault();
(replace the int?
with float?
or decimal?
or whatever it is that matches your data)
How to get average of list within lists using linq?
I have tested the solution I put in the update:
double average = busInCat.Max(b=> b.GetReviews().Average(r => r.getRateing()));
return busInCat.Where(b => b.GetReviews().Average(r => r.getRateing()) == average).T
The above code does indeed work as intended.
How to get Average of grouped results in Linq query
In the original query you probably want to do this.
//other code removed for brevity
select new {
Date = key,
Rating = g.Count() > 0 ? g.Average(x => x.Rating) : 0
};
And then return the result
return Json(ratingsByMonth);
how to calculate average for each item in a list with LINQ?
I'm a bit short on time to test it but I think it should work with a few small tweaks. If I've made any typos, let me know:
var listadoA = alumnos.GroupJoin(examenes,
a => a._id,
e => e._alumnoId,
(a, eGroup) => new
{
Alumno = a,
Examenes = eGroup
}).Where(p => p.Examenes.Count() >= 1).OrderBy(p => p.Alumno._nombre).ToList();
foreach (var obj in listadoA){
var promedio = obj.Examenes.Average(e => e._nota);
I'm curious why your fields starting with underscore are publicly accessible; that's the naming convention for a private field.. should really have public properties for them. Also, I've assumed that "nota" is the exam score..
Join and Calculate Average of column using LINQ to sql
var query = from video in Video join
comment in Comment on comment.VideoId equals video.VideoId;
Console.WriteLine("Average Rating: " + query
.Where(i => i.VideoName = videoName)
.Average(i => i.Rating));
Related Topics
Resharper Formatting: Align Equal Operands
Use Linq to Generate Direct Update Without Select
Wpf Controls Needed to Build Chess Application
How to Handle Forms Authentication Timeout Exceptions in ASP.NET
How to Set Chrome Preferences Using Selenium Webdriver .Net Binding
Newtonsoft.JSON Assembly Package Version Mismatch
String Compare C# - Whole Word Match
Concurrentdictionary Getoradd Async
C# - How to Detect a Windows Shutdown/Logoff and Cancel That Action (After Asking the User)
Dynamically Cross-Join Multiple Different-Size Collections Together in Linq (C#)
Is .Net 4.0 Compatible with Windows Xp Sp2 or Below
Does .Net Have a Built-In Eventargs<T>
Does Foreach Automatically Call Dispose
How to Terminate a Thread in C#