使用LINQ在两个日期之间过滤数据

时间:2011-06-01 10:05:43

标签: c# .net linq

如何在两个日期时间之间过滤数据。我在这里过滤目录中的文本文件长度。我需要在所选日期之间过滤文本文件。

DateTime startDate = dateTimePicker1.Value;
DateTime endDate = dateTimePicker2.Value;
var queryList1Only = from i in di.GetFiles("*.txt", SearchOption.AllDirectories)  
                     select i.Length;

有什么建议吗?

4 个答案:

答案 0 :(得分:5)

嗯,where条款怎么样?

var query = from i in di.GetFiles("*.txt", SearchOption.AllDirectories) 
            where (i.GetCreationTime() > startDate && i.GetCreationTime() < endDate)
            select i.Length;

答案 1 :(得分:5)

使用Where子句:

DateTime startDate = dateTimePicker1.Value;
DateTime endDate = dateTimePicker2.Value;

var queryList1Only = from i in di.GetFiles("*.txt", SearchOption.AllDirectories) 
                     where i.GetCreationTime() > startDate && i.GetCreationTime() < endDate
                     select i.Length;

您可以使用GetCreationTimeGetLastWriteTime来代替GetLastAccessTime

我建议使用where子句查看几个示例,以全面了解它的工作原理here

答案 2 :(得分:2)

from fi in new DirectoryInfo(@"c:\path").EnumerateFiles("*.txt")
where fi.CreationTime > startDate and fi.CreationTime < endDate)
select fi.FullName;

答案 3 :(得分:-1)

这对我有用

var data = (from dataperiod in period where dataperiod.DateStart <= (DateTime)finalDayNovelty && dataperiod.DateEnd >= (DateTime)initialDayNovelty select dataperiod ).ToList();