Reputation: 2490
I need to be able to query a local directory for the files that I add to it. The method that contains the LINQ Query will return the file whose create date is the oldest. So, the order of operation is basically a First-In First-Out scenario.
Note that I am returning a list because the requirements may change to return more than one file.
The code I've come up with to achieve most of this is as follows:
public static List<FileInfo> GetNextFileToProcess(DirectoryInfo directory)
{
var files = from f in directory.GetFiles()
orderby f.CreationTime ascending
select f;
return files.Cast<FileInfo>().ToList();
}
The problem is that I have not limited this list to containing and returning only the file whose index is 0 after determining the sort order.
Do I need a where clause to limit the oldest file from being returned or what?
Upvotes: 1
Views: 1266
Reputation: 338406
var files = (from f in directory.EnumerateFiles()
orderby f.CreationTime ascending
select f).Take(1);
Upvotes: 3
Reputation: 1503519
You've said you want to return a list in case you need more than one file later on - so why bother limiting it? You could use Take(1)
, but why not just return everything to the caller and let them decide what they want?
If you're going to limit it to "a list containing one element" you might as well make it just return a FileInfo
instead - you'll need to modify the code if you want to return more than one entry anyway.
Upvotes: 2