luckyluke
luckyluke

Reputation: 167

Return sorted directory folders by name

I have a directory path c:\W with a list of folders in it -

01_C
02_B
03_A
04_F

I would like the directory folders sorted and returned with below output -

A
B
C
F

I am using .net 4.

Upvotes: 0

Views: 2401

Answers (2)

Ric
Ric

Reputation: 13248

DirectoryInfo d = new DirectoryInfo(@"C:\W");
var sorted = d.GetDirectories().Select(f => f.Name.Split('_')[1]).OrderBy(name => name);

Please note that there isn't any error handling here, just an idea to get you rolling.

Upvotes: 0

Habib
Habib

Reputation: 223267

If you want to sort on the Last character of your directory name then:

DirectoryInfo di = new DirectoryInfo("c:\\w");
List<string> dirList = di.GetDirectories()
                         .Select(r => r.Name)
                         .OrderBy(r => r[r.Length - 1])
                         .ToList();

Remember to include using System.Linq on top.

Upvotes: 2

Related Questions