Ejemplo n.º 1
0
        public static double AverageforCategory(IEnumerable <MovementsViewModel> movements, string category, int?year = null, int?month = null, bool justExtrations = true)
        {
            var monthAndYaerMovements = ModelOperation.GetMovementByMonthYear(movements, year == 0 ? null : year, month == 0 ? null : month);

            double average = 0;

            //TODO get average for year / month for the category
            var movementsByCategory = monthAndYaerMovements.Where(mov => mov.Category == category && Math.Abs(mov.Amount) > 0);

            movementsByCategory = ModelConverter.GetMovementsViewModelsByType(justExtrations, movementsByCategory);

            if (movementsByCategory != null && movementsByCategory.Any())
            {
                //Years average
                if (month == null && year == null)
                {
                    var yearResult = movementsByCategory.GroupBy(mv => mv.DateTime.Year).Select(mov => new { Year = mov.Key, sum = mov.Sum(p => p.Amount) });
                    average = !yearResult.Any() ? 0 : yearResult.Average(r => r.sum);
                }

                // Get the months average
                if (month == 0)
                {
                    var monthResult = movementsByCategory.GroupBy(mv => mv.DateTime.Month).Select(mov => new { Month = mov.Key, sum = mov.Sum(p => p.Amount) });
                    average = !monthResult.Any() ? 0 : monthResult.Average(r => r.sum);
                }
                // Get the average of a specific month
                if (month != 0 && month != null)
                {
                    var monthResult = movementsByCategory.GroupBy(mv => mv.DateTime.Month).Select(mov => new { Month = mov.Key, sum = mov.Sum(p => p.Amount) });
                    average = !monthResult.Any() ? 0 : monthResult.Average(r => r.sum);
                }

                //if (year != null && month == 0)
                //{
                //    var monthResult = movementsByCategory.GroupBy(mv => mv.DateTime.Day).Select(mov => new { Month = mov.Key, sum = mov.Sum(p => p.Amount) });
                //    average = !monthResult.Any() ? 0 : monthResult.Average(r => r.sum);
                //}


                if (year != null && (month != null && month != 0))
                {
                    average = movementsByCategory.Average(m => m.Amount);
                }
            }
            //return Math.Abs(average);
            return(average);
        }