Linq:选择当月数据,但检查是否需要结转前几个月的数据

时间:2018-08-13 10:03:54

标签: c# linq

我目前有这个linq:

var filterdForecastRevenue = filteredWonSales
    .Where(x => x.ProjectStartDate.Month.Equals(month.Month) 
                && x.ProjectStartDate.Year.Equals(month.Year));

foreach (var rev in filterdForecastRevenue)
{   
    if (rev.ProjectDurationMonths > 0)
    {
        rev.ForecastSell = rev.ForecastSell / rev.ProjectDurationMonths;
    }
}

var forecastRevenueTotal = (filterdForecastRevenue.Any()) 
                              ? filterdForecastRevenue.Sum(x => x.ForecastSell) : 0;

我的课:

public class WonSaleView
{
    [Key]
    public Guid Id { get; set; }
    public string Jobnumber { get; set; }
    public double ForecastSell { get; set; }
    public DateTime ProjectStartDate { get; set; }
    public int ProjectDurationMonths { get; set; }
}

这可行,但是我需要的是:
值需要从前几个月结转,例如,如果ProjectStartDate在7月,但要运行3个月(ProjectDurationMonths),我也需要在八月和九月结转计算ForecastSell。 / p>

我尝试了3个小时,试图找出这样一个简单的任务,任何帮助都很棒。

2 个答案:

答案 0 :(得分:0)

您正在将DateTime转换为整数(月,年)。最好使用DateTime对象。参见下面的代码:

DateTime now = DateTime.Now;
DateTime firstOfMonth = new DateTime(now.Year, now.Month, 1);

var filterdForecastRevenue = filteredWonSales
    .Where(x => (x.ProjectStartDate >= firstOfMonth) 
|| ((x.ProjectStartDate.AddMonths(rev.ProjectDurationMonths) >= firstOfMonth));

答案 1 :(得分:0)

如果正确理解,则需要在给定月份内处于“活动”状态的项目。 快速只能提出两个查询

var now = DateTime.Now();
var startMonth = new DateTime(now.Year, now.Month, 1);
var endMonth = startMonth.AddMonths(1).AddSeconds(-1);

var fullyOverlaping = 
   filteredWonSales.Where(sale => sale.ProjectStartDate < startMonth)
                   .Where(sale => sale.ProjectStartDate.AddMonths(rev.ProjectDurationMonths) > endMonth);

var withinMonth = 
   filteredWonSales.Where(sale => (sale.ProjectStartDate >= startMonth && sale.ProjectStartDate <= endMonth) ||
                         (sale.ProjectStartDate.AddMonths(rev.ProjectDurationMonths) >= startMonth && sale.ProjectStartDate.AddMonths(rev.ProjectDurationMonths) <= endMonth));

var all = withinMonth.Concat(fullyOverlaping);