Click here to Skip to main content
15,890,043 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to make ( Group by ) in ( Directory = Folder ) by C# ? ( or any other way )

Such as Group by Type , Date or Size ?

I have a lot of folders and I need to sort all of them by Type.

This is my picture for more details.


https://i.stack.imgur.com/PXXt2.png[^]

What I have tried:

I Can't Find Any Code and ask a lot of people
Posted
Updated 18-Aug-19 0:32am
Comments
Richard Deeming 22-Aug-19 9:48am    
Do you want to read a grouped list of files in C#? Or are you looking to change the Windows Explorer "group by" option from C#?
Richard Deeming 22-Aug-19 10:00am    
If you want to change the Windows Explorer view, there's some code in this StackOverflow thread[^] to do that. It's in Delphi - I'm not sure how easy it would be to convert it to C#.

1 solution

Try this:
C#
DirectoryInfo di = new DirectoryInfo(@"D:\Test Data");
FileInfo[] info = di.GetFiles();
Dictionary<string, List<FileInfo>> byType = info.GroupBy(i => i.Extension).ToDictionary(g => g.Key, g => g.ToList());
 
Share this answer
 
Comments
Maciej Los 19-Aug-19 2:04am    
5ed!
OriginalGriff 19-Aug-19 2:17am    
Embarrassingly, I had to work out how to do this from scratch - because I forgot until this morning that I wrote a tip on how to do this five years ago:

https://www.codeproject.com/Tips/778786/Using-Linq-to-create-a-Dictionary-of-sub-Lists-by

:sigh:
Maciej Los 19-Aug-19 2:48am    
:laugh:
Richard Deeming 22-Aug-19 9:46am    
I'd be inclined to use EnumerateFiles instead of GetFiles. GroupBy just enumerates over everything anyway, so there's no benefit to reading all of the files into an array first. :)

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