bala3569 bala3569 - 17 days ago 5
C# Question

Filter data between two dates using LINQ

How to filter data between two datetime. Here i am filtering the text file length in a directory..I need to filter text file between the selected date.

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


Any suggestion?

Answer

Use the Where clause:

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;

Instead of GetCreationTime you could use GetLastWriteTime or GetLastAccessTime.

I'd advise checking out a few examples using the where clause for a full understanding of how it all works here.

Comments