我想圓整一個平均Linq函數的結果,有可能嗎?圓平均Linq函數C#
public IEnumerable<GetLocationsAverageDTO> GetLocationsAverageByCompanyId(int id)
{
try
{
var baseQuery = _dbContext.Answers.AsNoTracking()
.Where(p => p.Location.Company.Id == id
&& p.Question.Type != QuestionType.Text)
.GroupBy(g => new { Location = g.Location.Name })
.Select(x =>
new GetLocationsAverageDTO
{
LocationName = x.Key.Location,
Average = x.Average(f => f.Numeric)
})
.OrderBy(x => x.LocationName);
var dto = baseQuery.ToList();
return dto;
}
catch (Exception error)
{
_logger.Error("[Error in SurveyService.GetLocationsAverageByCompanyId - id: " + id + " - Error: " + error + "]");
return null;
}
}
喜歡的東西
Average = x.Average(f => f.Numeric, 2) // result: 45,21
這不會有很多工作要做使用LINQ,更多的是與舍入數到所需的精度,無論它來自何方。 –
你不能使用'Math.Round(x.Average(f => f.Numeric),2);'? – Habib
任何請求將內存中的雙/十進制「舍入」,而不是將其格式化爲文本時,通常是錯誤的。你確定在這個確切點上需要它嗎? –