我的源数据包含月份数据,如下所示:
Oct 2011
Nov 2011
Dec 2011
Jan 2012
Feb 2012
我需要选择发票所适用的所有月份。发票具有以下属性:
Invoice.StartDate=13-10-2011;
Invoice.EndDate=11-01-2012;
sourceData.Where(x => x.SourceDate.Month >= Invoice.StartDate.Month &&
x.SourceDate.Year==Invoice.StartDate.Year &&
x.SourceDate.Month <= Invoice.EndDate.Month &&
x.SourceDate.Year == Invoice.EndDate.Year).ToList();
上面的查询返回0.我期待下面的过滤数据源结果:
Oct 2011
Nov 2011
Dec 2011
Jan 2012
有人可以帮助我实现上述目标吗?
答案 0 :(得分:1)
您处理了年份相同的情况,但您还必须处理年份大于开始年份的情况以及年份小于结束年份的情况:
sourceData.Where(x => (x.SourceDate.Year > Invoice.StartDate.Year ||
(x.SourceDate.Month >= Invoice.StartDate.Month &&
x.SourceDate.Year == Invoice.StartDate.Year)) &&
(x.SourceDate.Year < Invoice.EndDate.Year ||
(x.SourceDate.Month <= Invoice.EndDate.Month &&
x.SourceDate.Year == Invoice.EndDate.Year))).ToList();
此解决方案不易读取,容易出错,但它最接近原始解决方案。
答案 1 :(得分:0)
这一年是独一无二的。 2011年或2012年。 但是你的where子句设置了不可能的选项。
x.SourceDate.Year == Invoice.StartDate.Year && x.SourceDate.Year == Invoice.EndDate.Year
与
相同x.SourceDate.Year == 2011 && x.SourceDate.Year == 2012
这个怎么样?
sourceData.Where(x => (x.SourceDate.Month >= Invoice.StartDate.Month &&
x.SourceDate.Year==Invoice.StartDate.Year) ||
(x.SourceDate.Month <= Invoice.EndDate.Month &&
x.SourceDate.Year == Invoice.EndDate.Year)).ToList();
答案 2 :(得分:0)
您的代码会查找以下数据:
x.SourceDate.Month&gt; = Invoice.StartDate.Month 和 x.SourceDate.Year == Invoice.StartDate.Year 和 x.SourceDate.Month&lt; = Invoice.EndDate.Month 和 x.SourceDate.Year == Invoice.EndDate.Year
您的数据都不符合所有这些标准,您应该寻找以下内容:
(x.SourceDate.Month&gt; = Invoice.StartDate.Month AND x.SourceDate.Year == Invoice.StartDate.Year) 要么 (x.SourceDate.Month&lt; = Invoice.EndDate.Month AND x.SourceDate.Year == Invoice.EndDate.Year)
像这样:
sourceData.Where(x => (x.SourceDate.Month >= Invoice.StartDate.Month &&
x.SourceDate.Year==Invoice.StartDate.Year) ||
(x.SourceDate.Month <= Invoice.EndDate.Month &&
x.SourceDate.Year == Invoice.EndDate.Year)).ToList();
答案 3 :(得分:0)
难道你不能只进行日期比较吗?我不确定源表中的值是否是实际日期项,但是如果需要,您始终可以使用Date()
构造函数来构建正确的日期。
sourceData.Where(x => x.SourceDate >= Invoice.StartDate &&
x.SourceDate <= Invoice.EndDate ).ToList();