我有一个特定时间段的服务销售列表(activationDate 到 endDate)。我需要生成按月/年分组的销售报告(例如 2012 年 4 月)。对于每个月,我想显示整月的使用量和天数。
我的课:
public class SaleMonth
{
public DateTime MonthYear { get; set; }//.ToString("Y")
public int FullMonth { get; set; }
public int DaysMonth { get; set; }
public string TotalMonths { get { return String.Format("{0:N2}",
(((FullMonth * 30.5) + DaysMonth) / 30.5)); } }
}
我试过的:
using (CompanyContext db = new CompanyContext())
{
var saleList = db.MySales.ToList();
DateTime from = saleList.Min(s => s.ActivationDate),
to = saleList.Max(s => s.EndDate);
for (DateTime currDate = from.AddDays(-from.Day + 1)
.AddTicks(-from.TimeOfDay.Ticks);
currDate < to;
currDate = currDate.AddMonths(1))
{
var sm = new SaleMonth
{
MonthYear = currDate,
FullMonth = 0,
DaysMonth = 0
};
var monthSell = saleList.Where(p => p.ActivationDate < currDate.AddMonths(1)
|| p.EndDate > currDate);
foreach (var sale in monthSell)
{
if (sale.ActivationDate.Month == sale.EndDate.Month
&& sale.ActivationDate.Year == sale.EndDate.Year)
{//eg 4/6/13 - 17/6/13
sm.DaysMonth += (sale.EndDate.Day - sale.ActivationDate.Day + 1);
}
else
{
if (sale.ActivationDate.Year == currDate.Year
&& sale.ActivationDate.Month == currDate.Month)
sm.DaysMonth += (currDate.AddMonths(1) - sale.ActivationDate).Days;
else if (sale.EndDate.Year == currDate.Year
&& sale.EndDate.Month == currDate.Month)
sm.DaysMonth += sale.EndDate.Day;
else if(sale.ActivationDate.Date <= currDate
&& sale.EndDate > currDate.AddMonths(1))
sm.FullMonth++;
}
}
vm.SaleMonthList.Add(sm);
}
}
我有一种感觉,我在这里遗漏了一些东西,必须有一种更优雅的方式来做到这一点。
这是一张图片,显示了一些销售和从中生成的报告。