I have a LINQ statement that use average on grade, but the problem is that sometimes
grade gets like 3.777777 displayed, but I would like it to be 3.7 how can I truncate it in my linq statement?
this is my LINQ statement:
public List<CoreValueAndAverageGrade> GetAverageGradeForAllCoreValues2()
{
var answers = db.GoalCardQuestionAnswer
.Where(answer => answer.Grade.HasValue
&& (answer.SelectedQuestion.Question is CoreValueQuestion
&& (answer.SelectedQuestion.Question as CoreValueQuestion).SubjectType.Ignored_Statistic == false));
var groupedByCoreValue = answers.GroupBy(answer => (answer.SelectedQuestion.Question as CoreValueQuestion).CoreValue);
return groupedByCoreValue
.OrderBy(group => group.Key.Name)
.Select(group => new CoreValueAndAverageGrade
{
CoreValue = group.Key,
AverageGrade = group.Any() ? group.Average(answer => answer.Grade.Value) : 0
}).ToList();
Maby its possible to do it inside the controller in my action method?
var averageGrades = OfficeStatisticRepository.GetAverageGradeForAllCoreValues2();
var dataItems = (averageGrades.Select(averageGrade => averageGrade.AverageGrade).ToArray()); // here
You have three options here.
1) Round in the Linq query using
Math.TruncateJust like you would useAverageorAggregate. as part of the Linq->SQL translation.Funny that the docs mention a
System.Math.Truncate(decimal, int)method, but that it doesn’t actually exist… Luckily you can just multiply and round. This will work fine for Decimals, but if your grade is a Double, it might cause new rounding issues because of the division.2) Round the values in your Linq query after calling ToList using decimal.Round (be sure to pick the right rounding direction, for grades you won’t want to use bankers rounding.
3) Keep the values unchanged and only display the rounded value in your UI using a display format such as
F1on the textbox/label/binding you’re using to display the value. How you’ll set this up is dependent on the display framework you’re using. This will not combine values if there’s a 3.77 and a 3.76 in the group.