Reputation: 15557
So I have this routine:
public static IEnumerable<string> GetFiles( string path, string[] searchPatterns, SearchOption searchOption = SearchOption.TopDirectoryOnly) {
return searchPatterns.AsParallel()
.SelectMany(searchPattern =>
Directory.EnumerateFiles(path, searchPattern, searchOption))
.OrderBy<string, string>( (f) => f)
.Distinct<string>();
}
and its working but ordering the files by its name and I need to order the files returned by its creation date. How can I sort by that if the item is an string like in the routine. I want to use Enumerate cause files are expected to be more than 1k.
Thanks.
Upvotes: 12
Views: 13488
Reputation: 69958
Examples below:
DirectoryInfo dir = new DirectoryInfo(path);
//Date created latest first
var files = dir.EnumerateFiles().OrderByDescending(x => x.CreationTime);
//Date created latest last
var files2 = dir.EnumerateFiles().OrderBy(x => x.CreationTime);
//dir.EnumerateFiles() is the same as the ones below
var files3 = dir.EnumerateFiles("*");
var files4 = dir.EnumerateFiles("*", SearchOption.TopDirectoryOnly);
Upvotes: 1
Reputation: 8037
I'm not sure you really want to be using the Task Parallel Library for that query. For some reasons, see this question How to find all exe files on disk using C#?.
As for enumerating the files by creation date, I would start the function by creating a new DirectoryInfo using the path provided, and then call .EnumerateFiles(string pattern, SearchOption searchOption) to get all the files matching your pattern. Finally, you can order by the CreationTime property of the FileInfo objects in the returned enumeration and then either return the full FileInfo objects, or just their Name, like so:
public static IEnumerable<string> GetFiles( string path, string[] searchPatterns, SearchOption searchOption = SearchOption.TopDirectoryOnly) {
DirectoryInfo dir = new DirectoryInfo(path);
var dirs = (from file in dir.EnumerateFiles(searchPatterns, searchOptions)
orderby file.CreationTime ascending
select file.Name).Distinct(); // Don't need <string> here, since it's implied
return dirs;
}
Note: I don't have access to a compiler at the moment, but I believe the above code is error free.
Upvotes: 20
Reputation: 564373
You need to switch to using DirectoryInfo.EnumerateFiles, which will return a collection of FileInfo instances. You can then sort these by dates and select out the names.
Upvotes: 5