2010-07-06 225 views
0

設置,我有以下LINQ查詢:在一個聚合結果聚合函數使用LINQ

var totalAmountsPerMonth =    
       from s in Reports() 
       where s.ReportDate.Value.Year == year 
       group s by s. ReportDate.Value.Month into g 
       orderby g.Key 
       select new 
       { 
        month = g.Key, 
        totalRecaudacion = g.Sum(rec => rec.RECAUDACION), 
        totalServicios = g.Sum(ser => ser.SERVICIOS) 
       }; 

var final = new ResultSet 
      { 
       Recaudacion = meses.Average(q => q. totalRecaudacion), 
       Servicios = meses.Average(o => o. totalServicios) 
      }; 

,我需要獲得「RECAUDACION」,每月的「SERVICIOS」總量的平均值。我做了這個查詢。但是,我絕對認爲這不是最好的解決方案。您能否建議我採用更好更高效的方法(如果可能,請在單個查詢中)獲取這些數據?

回答

1

我已經創建了一個簡單的擴展方法。事實證明,這是一個簡單的秒錶基準測試的兩倍效率。

public class Report 
{ 
    public DateTime? Date { get; set; } 

    public int RECAUDACION { get; set; } 

    public int SERVICIOS { get; set; } 
} 

static class EnumerableEx 
{ 
    public static Tuple<double, double> AveragePerMonth(this IEnumerable<Report> reports) 
    { 
     var months = new HashSet<int>(); 
     double RECAUDACION = 0d; 
     double SERVICIOS = 0d; 

     foreach (Report rep in reports) 
     { 
      if (!months.Contains(rep.Date.Value.Month)) 
      { 
       months.Add(rep.Date.Value.Month); 
      } 

      RECAUDACION += rep.RECAUDACION; 
      SERVICIOS += rep.SERVICIOS; 
     } 

     var totalMonth = months.Count; 

     if (months.Count > 0) 
     { 
      RECAUDACION /= totalMonth; 
      SERVICIOS /= totalMonth; 
     } 

     return Tuple.Create<double, double>(RECAUDACION, SERVICIOS); 
    } 
}