![](/img/trans.png)
[英]How to get all records within the last Two Days from the current Date using EF 4?
[英]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月运行代码,则应该将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年],请从“当前月份”开始选择数据。 否则,如果年份为当前年份,请从本月之前的月份中选择数据。
一个有效的例子:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.