从当前日期获取过去一年内修改的记录

Get records modified within the last year from current date

我有一个结构如下的结果集。

List<BudgtedData> budgetData;
public class BudgtedData
{
    public decimal BudgetedCpmDataId { get; set; }
    public int ForecastYear { get; set; }
    public int ForecastMonth { get; set; }
}

我想获取去年的记录。例如,如果我 运行 2015 年 3 月的代码,它应该 return 2014 年 3 月到 2015 年 2 月 .我如何在 linq

中实现这一点

我认为这段代码应该适合你:

int currentYear = DateTime.Now.Year; int currentMonth = DateTime.Now.Month;

var result = budgetData.Where(
       b => (b.ForecastYea.Equals(currentYear - 1)  
             && b.ForecastMonth >= currentMonth )
             ||(b.ForecastYear.Equals(currentYear)                       
             && b.ForecastMonth <= currentMonth - 1))
             .ToList();

这是解决方案:

var res = budgetData.Where(r => ((r.ForecastYear == (DateTime.Today.Year - 1) && r.ForecastMonth >= DateTime.Today.Month) || (r.ForecastYear == DateTime.Today.Year && r.ForecastMonth < DateTime.Today.Month))).ToList();

解释:如果年份是一年前[2015 年是 2014 年]select 从当月开始的数据。否则,如果年份是当年,则 select 本月之前月份的数据。

一个工作示例:

 List<BudgtedData> budgetData = new List<BudgtedData>();
 budgetData.Add(new BudgtedData() { BudgetedCpmDataId = 1, ForecastMonth = 12, ForecastYear = 2014 });
 budgetData.Add(new BudgtedData() { BudgetedCpmDataId = 1, ForecastMonth = 1, ForecastYear = 2014 });
 budgetData.Add(new BudgtedData() { BudgetedCpmDataId = 1, ForecastMonth = 1, ForecastYear = 2013 });
 budgetData.Add(new BudgtedData() { BudgetedCpmDataId = 2, ForecastMonth = 2, ForecastYear = 2014 });
 budgetData.Add(new BudgtedData() { BudgetedCpmDataId = 2, ForecastMonth = 1, ForecastYear = 2015 });


 var res = budgetData.Where(r => ((r.ForecastYear == (DateTime.Today.Year - 1) && r.ForecastMonth >= DateTime.Today.Month) || (r.ForecastYear == DateTime.Today.Year && r.ForecastMonth < DateTime.Today.Month))).ToList();

 foreach (BudgtedData item in res)
 {
     Console.WriteLine(item.ForecastYear + "  "+ item.ForecastMonth);
 }

输出:

 2014 12
 2014 2
 2015 1