Filter a directory for .csv files using c# lambda

2019-06-06 16:55发布

问题:

Help me improve the lambda below with adding another conditon like

Get me all .csv with no matching .wav file. Example, say "sample.csv" and "sample.wav", then I dont want to collect "sample.csv".

Files = new DirectoryInfo(txtStartPath.Text)
           .EnumerateFiles("*.csv")
           .Where(file => file.CreationTime < DateTime.Now.AddDays(-ageOfFile))
           .ToList();

回答1:

You have to get list of wav files first:

var wavFiles = new DirectoryInfo(txtStartPath.Text)
                   .EnumerateFiles("*.wav")
                   .Select(f => Path.GetFileNameWithoutExtension(f))
                   .ToList();

and then you can use it as part of Where condition:

Files = new DirectoryInfo(txtStartPath.Text)
           .EnumerateFiles("*.csv")
           .Where(f => f.CreationTime < DateTime.Now.AddDays(-ageOfFile))
           .Where(f => !wacFiles.Contains(Path.GetFileNameWithoutExtension(f)))
           .ToList();


标签: c# lambda