我需要从一个特定的文件夹中获取所有目录,其日期范围如下:
开始日期<=Dir.CreatedDate<=结束日期
我正试图用GetDirectories
方法进行过滤,但运气不佳:
RootDirInfo.GetDirectories()
.Where(x => new DirectoryInfo(x).CreationTime.Date == DateTime.Today.Date);
让我将其拆分为多个函数,使其更加清晰(并且不会创建多个对象):
private static bool IsInRange(DateTime time, DateTime min, DateTime max)
{
return time >= min && time <= max;
}
现在使用LINQ,您可以简单地编写:
public static IEnumerable<DirectoryInfo> GetDirectories(
DirectoryInfo directory,
DateTime startDate,
DateTime endDate)
{
return directory.GetDirectories()
.Where(x => IsInRange(x.CreationTime, startDate, endDate));
}
如果你想要它紧凑:
public static IEnumerable<DirectoryInfo> GetDirectories(
DirectoryInfo directory,
DateTime startDate,
DateTime endDate)
{
return directory.GetDirectories()
.Where(x => x.CreationTime >= startDate && x.CreationTime <= endDate);
}
最后注意:您正在执行new DirectoryInfo(x)
,但它是错误的,因为我假设RootDirInfo
是DirectoryInfo
,那么GetDirectories()
将返回准备使用的DirectoryInfo[]
(请参阅我的最后一个代码片段)。
类型System.DateTime
确实支持运算符>=
和<=
,因此您可以使用它们进行比较:
RootDirInfo.GetDirectories()
.Where(x => x.CreationTime >= startDate && new x.CreationTime <= endDate);