0

我有一个包含月份数据的源数据,如下所示:

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

有人可以帮我实现上述目标吗?

4

5 回答 5

2

该解决方案只是创建设置为 0DateTime的 s,Day以便可以直接比较它们。它使用查询语法,因为它更方便创建新DateTime的 s。

startYearMonth = new DateTime(Invoice.StartDate.Year, Invoice.StartDate.Month, 0);
endYearMonth = new DateTime(Invoice.EndDate.Year, Invoice.EndDate.Month, 0);

(from data in sourceData
 let dataYearMonth = new DateTime(data.SourceDate.Year, data.SourceDate.Month, 0)
 where dataYearMonth >= startYearMonth && dataYearMonth <= endYearMonth
 select data).ToList();
于 2012-09-10T03:16:15.880 回答
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();

这个解决方案不那么可读并且容易出错,但它最接近您的原始解决方案。

于 2012-09-10T03:01:37.003 回答
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();
于 2012-09-10T01:55:38.573 回答
0

您的代码在以下位置查找数据:

x.SourceDate.Month >= Invoice.StartDate.Month AND x.SourceDate.Year==Invoice.StartDate.Year AND x.SourceDate.Month <= Invoice.EndDate.Month AND x.SourceDate.Year == Invoice.EndDate。年

您的数据都不符合所有这些标准,您应该寻找以下内容:

(x.SourceDate.Month >= Invoice.StartDate.Month AND x.SourceDate.Year==Invoice.StartDate.Year) OR (x.SourceDate.Month <= 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();
于 2012-09-10T02:03:28.857 回答
0

你不能做一个日期比较吗?我不确定源表中的值是否是实际日期项,但Date()如有必要,您始终可以使用构造函数来构建正确的日期。

sourceData.Where(x => x.SourceDate >= Invoice.StartDate && 
                 x.SourceDate <= Invoice.EndDate ).ToList();
于 2012-09-10T03:09:41.643 回答