Click here to Skip to main content
15,893,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I cannot combine the effects of selecting file extensions and sorting

What I have tried:

C#
//Allowed extension

var allowedExtensions = new[] { ".jpg", ".jpe", ".bmp", ".gif", ".png", ".jpeg", ".mp4", ".flv", ".wav", ".mp3" };

//read files by extension rule (where ...)
var files = Directory
            .GetFiles(path)                
            .Where(file => allowedExtensions.Any(file.ToLower().EndsWith))
            -->  .OrderBy(file => file.LastWriteTime) <-- this wrong 
            .ToList();


//example to read in date order

var sortedFiles = new DirectoryInfo(@path).GetFiles()                
                 .OrderBy(f => f.LastWriteTime)
                 .ToList();

how can I add OrderBy After Where .... ?
Posted
Updated 19-Mar-21 7:33am
v2

This is one of the good reasons for not using var all the time ...
Directory.GetFiles returns an array of strings, not FileInformation objects.
And strings don't have a LastWriteTime property.

Try using DirectoryInfo:
C#
DirectoryInfo directoryInfo = new DirectoryInfo(path);
var files = directoryInfo.GetFiles()
            .Where(file => allowedExtensions.Any(file.Extension.ToLower().EndsWith))
            .OrderBy(file => file.LastWriteTime)
            .ToList();
 
Share this answer
 
Comments
Richard MacCutchan 19-Mar-21 13:11pm    
Quote:This is one of the good reasons for not using var all the time ...Hmm!
OriginalGriff 19-Mar-21 13:27pm    
If he'd used an explicit type - string[] or FileInformation[] - it would have been obvious. The first would tell him "it's a string, it doesn't have a write time", the second and the compiler would have told him "you can't cast a string[] to a FileInformation[]".

Not caring what your data type is because "the system will sort it out and it's easier to type" is a big mistake!
Richard MacCutchan 19-Mar-21 13:33pm    
My comment was alluding to your use of var in your sample code. :)
OriginalGriff 19-Mar-21 13:36pm    
What can I say? I copy'n'pasted without thinking ... :laugh:
Maciej Los 21-Mar-21 6:04am    
You've made me sad ;(
The answer is correct even if the copy of code was made "without thinking".
5ed!
Directory.GetFiles Method (System.IO) | Microsoft Docs[^] returns an array of Strings. And String objects do not have a LastWriteTime property.
 
Share this answer
 
Comments
Maciej Los 21-Mar-21 6:04am    
5ed!
Short And To The Point!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900