我想对平均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;
}
}
像
这样的东西Average = x.Average(f => f.Numeric, 2) // result: 45,21
答案 0 :(得分:3)
我真的不知道Rounding是否在SQL-Providers中被翻译,但你可以在内存中进行迭代并使用Math.Round()
,它适用于所有情况:
var dto = baseQuery.ToList();
foreach(var item in dto)
{
item.Average = Math.Round(item.Average , 2);
}
答案 1 :(得分:1)
您可以简单地应用Math.Round()函数,该函数接受第二个参数,指示Linq查询结束时所需的小数位数。
Average = Math.Round(x.Average(f => f.Numeric), 2);
答案 2 :(得分:0)
只需将x.Average
包裹在Math.Round
.Select(x =>
new GetLocationsAverageDTO
{
LocationName = x.Key.Location,
Average = Math.Round(x.Average(f => f.Numeric), 2)
})