gpt4 book ai didi

带日期过滤器的 C# GetFiles

转载 作者:太空狗 更新时间:2023-10-29 22:03:38 25 4
gpt4 key购买 nike

是否有更有效的方法来从带有日期过滤器的目录中填充文件名列表?

目前,我正在这样做:

foreach (FileInfo flInfo in directory.GetFiles())
{
DateTime yesterday = DateTime.Today.AddDays(-1);
String name = flInfo.Name.Substring(3,4);
DateTime creationTime = flInfo.CreationTime;
if (creationTime.Date == yesterday.Date)
yesterdaysList.Add(name);
}

这会遍历文件夹中的每个文件,我觉得应该有更多高效的方式。

最佳答案

第一个解决方案:

您可以使用 LINQ:

List<string> yesterdaysList = directory.GetFiles().Where(x => x.CreationTime.Date == DateTime.Today.AddDays(-1))
.Select(x => x.Name)
.ToList();

那么你可以直接使用这个名字列表。

第二种解决方案:

另一种使其更快的解决方案可能是:

DateTime yesterday = DateTime.Today.AddDays(-1); //initialize this variable only one time

foreach (FileInfo flInfo in directory.GetFiles()){
if (flInfo.CreationTime.Date == yesterday.Date) //use directly flInfo.CreationTime and flInfo.Name without create another variable
yesterdaysList.Add(flInfo.Name.Substring(3,4));
}

基准:

我使用这段代码做了一个基准测试:

class Program {
static void Main( string[ ] args ) {
DirectoryInfo directory = new DirectoryInfo( @"D:\Films" );
Stopwatch timer = new Stopwatch( );
timer.Start( );

for ( int i = 0; i < 100000; i++ ) {
List<string> yesterdaysList = directory.GetFiles( ).Where( x => x.CreationTime.Date == DateTime.Today.AddDays( -1 ) )
.Select( x => x.Name )
.ToList( );
}

timer.Stop( );
TimeSpan elapsedtime = timer.Elapsed;
Console.WriteLine( string.Format( "{0:00}:{1:00}:{2:00}", elapsedtime.Minutes, elapsedtime.Seconds, elapsedtime.Milliseconds / 10 ) );
timer.Restart( );

DateTime yesterday = DateTime.Today.AddDays( -1 ); //initialize this variable only one time
for ( int i = 0; i < 100000; i++ ) {
List<string> yesterdaysList = new List<string>( );

foreach ( FileInfo flInfo in directory.GetFiles( ) ) {
if ( flInfo.CreationTime.Date == yesterday.Date ) //use directly flInfo.CreationTime and flInfo.Name without create another variable
yesterdaysList.Add( flInfo.Name.Substring( 3, 4 ) );
}
}


timer.Stop( );
elapsedtime = timer.Elapsed;
Console.WriteLine( string.Format("{0:00}:{1:00}:{2:00}", elapsedtime.Minutes, elapsedtime.Seconds, elapsedtime.Milliseconds / 10));
timer.Restart( );

for ( int i = 0; i < 100000; i++ ) {
List<string> list = new List<string>( );

foreach ( FileInfo flInfo in directory.GetFiles( ) ) {
DateTime _yesterday = DateTime.Today.AddDays( -1 );
String name = flInfo.Name.Substring( 3, 4 );
DateTime creationTime = flInfo.CreationTime;
if ( creationTime.Date == _yesterday.Date )
list.Add( name );
}
}

elapsedtime = timer.Elapsed;
Console.WriteLine( string.Format( "{0:00}:{1:00}:{2:00}", elapsedtime.Minutes, elapsedtime.Seconds, elapsedtime.Milliseconds / 10 ) );
}
}

结果:

First solution: 00:19:84
Second solution: 00:17:64
Third solution: 00:19:91 //Your solution

关于带日期过滤器的 C# GetFiles,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11942979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com