我想对 Average Linq 函数的结果进行四舍五入,可以吗?
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;
}
}
Run Code Online (Sandbox Code Playgroud)
就像是
Average = x.Average(f => f.Numeric, 2) // result: 45,21
Run Code Online (Sandbox Code Playgroud)
您可以简单地应用Math.Round()函数,该函数接受第二个参数,该参数指示您想要的 Linq 查询末尾的小数位数。
Average = Math.Round(x.Average(f => f.Numeric), 2);
Run Code Online (Sandbox Code Playgroud)
我真的不知道舍入是否在 SQL-Providers 中进行了翻译,但您可以进行内存中迭代并使用Math.Round()它在所有情况下都有效:
var dto = baseQuery.ToList();
foreach(var item in dto)
{
item.Average = Math.Round(item.Average , 2);
}
Run Code Online (Sandbox Code Playgroud)