2016-07-27 82 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) 
})