我有一个结果集,其结构如下。
List<BudgtedData> budgetData;
public class BudgtedData
{
public decimal BudgetedCpmDataId { get; set; }
public int ForecastYear { get; set; }
public int ForecastMonth { get; set; }
}
我想在去年获得记录。例如,如果我在2015年3月运行代码,它应该返回2014年3月到2015年2月 。我如何在linq中实现这一目标
答案 0 :(得分:1)
我认为此代码适合您:
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();
答案 1 :(得分:0)
这是解决方案:
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年],请选择当前月份的数据。如果年份是当前年份,请选择本月之前几个月的数据。
一个工作示例:
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