C#GetFiles .Where(日期范围)

时间:2018-03-12 12:55:25

标签: c#

我正在尝试显示上周,周一至周五之间创建的Excel文件。例如,如果是星期一,我想在上周一和周五之间查找文件。如果它是同一周的星期五,我想查询相同的时间范围。

我知道以下代码会给我昨天的结果,但我如何获得日期范围?感谢。

string[] files = Directory.GetFiles(FBD.SelectedPath, "*.xls")
   .Where(file => new FileInfo(file).CreationTime.Date == DateTime.Today.AddDays(-1))
   .ToArray();

4 个答案:

答案 0 :(得分:1)

首先,您需要检查DateTime.Now.Day以获取星期几,然后添加或减去x天数来创建范围并向.where添加AND子句:

  //Add AND clause to .where and add or subtract days occordingly to create range, instead of using == you would use <= end and >= start
    string[] files = Directory.GetFiles(FBD.SelectedPath, "*.xls")
       .Where(file => new FileInfo(file).CreationTime.Date >= DateTime.Today.AddDays(-1) && new FileInfo(file).CreatTime.Date <= DateTime.Today.AddDays(1)
       .ToArray();

答案 1 :(得分:0)

<不仅可以与>相媲美,还可以与DateTime lastMonday = DateTime.Today.StartOfWeek(DayOfWeek.Monday); if(lastMonday == DateTime.Today) lastMonday = lastMonday.AddDays(-7); DateTime lastFriday = lastMonday.AddDays(4); string[] files = Directory.GetFiles(FBD.SelectedPath, "*.xls") .Select(f => new { File = f, CreationDate = File.GetCreationTime(f).Date }) .Where(x => x.CreationDate >= lastMonday && x.CreationDate <= lastFriday) .Select(x => x.File) .ToArray(); StartOfWeek相媲美。我会使用更便宜的File.GetCreationTime method

const SplashPageContainer = compose(
  connect(mapStateToProps, null),
  withDrawer({label: 'Splash', title: 'Lynked App'}),
  withTabs()
)(SplashPage);

使用this The component for route 'Splash' must be a React component. For example: import MyScreen from './MyScreen'; ... Splash: MyScreen, } 方法。

答案 2 :(得分:0)

var fileInfos = Directory.GetFiles(FBD.SelectedPath, "*.xls").Select(file => new FileInfo(file));

var files = fileInfos
                .Where(fi => fi.CreationTime.Date >= DateTime.Today.AddDays((int)DayOfWeek.Monday - (int)DateTime.Today.DayOfWeek - 7) 
                       && 
                       fi.CreationTime.Date < DateTime.Today.AddDays((int)DayOfWeek.Saturday - (int)DateTime.Today.DayOfWeek) - 7)
                .ToArray();

检查是否必须&lt; DateTime.Today.AddDays((int)DayOfWeek.Saturday - (int)DateTime.Today.DayOfWeek) - 7) 如果您考虑小时,因为DateTime.Today会在凌晨12:00:00给你,所以如果你输入&lt; = DateTime.Today.AddDays((int)DayOfWeek.Friday - (int)DateTime.Today.DayOfWeek) - 7),那么如果该字段有小时将无法正常工作。< / p>

否则(不考虑小时)你可以这样做&lt; = DateTime.Today.AddDays((int)DayOfWeek.Friday - (int)DateTime.Today.DayOfWeek) - 7)

答案 3 :(得分:-1)

类似的东西:

string [] files = Directory.GetFiles(FBD.SelectedPath,“* .xls”)    .Where(file =&gt; new FileInfo(file).CreationTime.Date&gt; = DateTime.Today.AddDays(-2)&amp;&amp; new FileInfo(file).CreationTime.Date&lt; = DateTime.Today.AddDays( -1))    .ToArray();