2016-07-27 133 views
-3

我想圆整一个平均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 
+0

这不会有很多工作要做使用LINQ,更多的是与舍入数到所需的精度,无论它来自何方。 –

+4

你不能使用'Math.Round(x.Average(f => f.Numeric),2);'? – Habib

+0

任何请求将内存中的双/十进制“舍入”,而不是将其格式化为文本时,通常是错误的。你确定在这个确切点上需要它吗? –

回答

1

您可以简单地套用Math.Round()功能,接受指示要将LINQ查询结束小数的位数第二个参数。

Average = Math.Round(x.Average(f => f.Numeric), 2); 
2

我真的不知道,如果舍入在SQL的提供翻译,但你可以做一个内存中的迭代和使用Math.Round()这在所有情况下工作:

var dto = baseQuery.ToList(); 
foreach(var item in dto) 
{ 
    item.Average = Math.Round(item.Average , 2); 
} 
+0

没有理由在这里调用.ToList()。 –

+0

@EricJ。但我们需要将这些项目存储在某个列表中。否则,项目在循环结束时丢失。 – user3185569

+0

@ user3185569无论如何,它们都会丢失,除非'ToList'的结果存储在别的地方。 – Kyle

0

只是包装x.AverageMath.Round

.Select(x => 
new GetLocationsAverageDTO 
{ 
    LocationName = x.Key.Location, 
    Average = Math.Round(x.Average(f => f.Numeric), 2) 
})