简体   繁体   中英

Get records modified within the last year from current date

I have a result set which has structure as follows.

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

I want to get the records within the last year. For example If I run the code in 2015 March it should return 2014 March to 2015 Feb .How I can achieve this in linq

I think this code should work for you:

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

This is the solution :

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

Explanation : If the year is one year back [for 2015 it's 2014] select data from Current month onward. Else if the year is current year, select data from months prior to this month.

A working Example :

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

Output :

 2014 12
 2014 2
 2015 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM