简体   繁体   English

.where(Date.AddHours)过滤器似乎不起作用

[英].Where(Date.AddHours) filter doesn't seem to work

I'm sorting a list of files that was created from yesterday 1:00pm to present time. 我正在整理从昨天下午1:00到现在的文件列表。 I'm trying to use the following code: The messagebox shows the correct time I'm trying to reference, but the filter doesn't seem to work. 我正在尝试使用以下代码:消息框显示了我正在尝试引用的正确时间,但是过滤器似乎无法正常工作。 If I remove the "AddHours(13)" it does filter correctly. 如果我删除“ AddHours(13)”,它将正确过滤。

MessageBox.Show(DateTime.Now.Date.AddDays(-1).AddHours(13).ToString());
string[] files = Directory.GetFiles(FBD.SelectedPath, "*.xls")
    .Where(file => new FileInfo(file).CreationTime.Date >= (DateTime.Now.Date.AddDays(-1).AddHours(13)) && file.Contains("AA"))
    .OrderBy(file => new FileInfo(file).CreationTime.Date)
    .ToArray(); 

What am I missing? 我想念什么?

DateTime.Now.Date.AddDays(-1).AddHours(13) will return 1pm... but you're checking against new FileInfo(file).CreationTime.Date , which is always at midnight... for a file created yesterday, it will be yesterday at midnight. DateTime.Now.Date.AddDays(-1).AddHours(13)将返回1pm ...,但是您正在检查new FileInfo(file).CreationTime.Date ,该new FileInfo(file).CreationTime.Date始终位于午夜...对于所创建的文件昨天,将是昨天的午夜。

So yes, you're filtering out that file. 是的,您正在过滤该文件。 If you remove the .Date part from new FileInfo(file).CreationTime that may well be all you need to do. 如果new FileInfo(file).CreationTime中删除.Date部分,则可能就是您所需要做的。

As a side-note, I'd use DateTime.Today instead of DateTime.Now.Date , and I'd also try to avoid evaluating it multiple times. 作为一个旁注,我将使用DateTime.Today而不是DateTime.Now.Date ,并且我还将尝试避免对其进行多次评估。 I'd also use DirectoryInfo and stick to FileInfo entries given that you're already creating those twoce. 如果您已经创建了Twoce,我也将使用DirectoryInfo并坚持使用FileInfo条目。 I'd rewrite your query as something like: 我会将您的查询重写为:

var cutoff = DateTime.Today.AddDays(-1).AddHours(13);
FileInfo[] files = new DirectoryInfo(FBD.SelectedPath).GetFiles("*.xls")
    .Where(file => file.CreationTime >= cutoff)
    .OrderBy(file => file.CreationTime)
    .ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM