tags:

views:

60

answers:

1

I have the following linq query:

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)
            };

And I need to obtain the average of the total amount of “RECAUDACION” and “SERVICIOS” of each month. I made this query. However, I definitely think this is not the best solution at all. Could you please suggest me a better and more efficient approach (in a single query if possible) to get these data?

+1  A: 

I have created a simple extension method. And it turns out to be two times more efficient in a simple stopwatch benchmark.

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);
    }
}
Yury Tarabanko