Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Sorting Directory Names using LINQ

Tags:

c#

linq

.net-4.0

I found something similar here but have been unable to get it working. I'm very new to LINQ and so not entirely sure what's going on with it. Any help would be appreciated. I have directory names like:

directory-1
article-about-something-else

I want to sort these by name but have been unable thus far. They are on a network drive residing on a RedHat server. The directory listing comes in a garbled mess in a seemingly random order.

Here's some of what I've tried:

DirectoryInfo dirInfo = new DirectoryInfo("Z:\\2013");
var dirs = dirInfo.GetDirectories().OrderBy(d => dirInfo.Name);
foreach (DirectoryInfo dir in dirs)
{
    string month = dir.Name;
    Console.WriteLine(dir.Name);
    var monthDirInfo = new DirectoryInfo("Z:\\2013\\" + month);
    var monthDirs = monthDirInfo.GetDirectories().OrderBy(d => monthDirInfo.CreationTime);
    foreach (DirectoryInfo monthDir in monthDirs)
    {
        string article = monthDir.Name;
        Console.WriteLine(monthDir.Name);
        sb.AppendLine("<li><a href=\"/2013/" + month + "/" + article + "\">" + TextMethods.GetTitleByUrl("2013/" + month + "/" + article) + "</a></li>");
    }
}

Any help would be greatly appreciated. I'm sort of at a loss at the moment. I'm sure I'm missing something obvious, too.

like image 889
ahwm Avatar asked Dec 27 '22 01:12

ahwm


1 Answers

You are ordering by the name of your root folder instead of the name of each sub-directory.

So change...

var dirs = dirInfo.GetDirectories().OrderBy(d => dirInfo.Name);

to ...

var dirs = dirInfo.EnumerateDirectories().OrderBy(d => d.Name);

and

var monthDirs = monthDirInfo.GetDirectories()
    .OrderBy(d => monthDirInfo.CreationTime);

to ...

var monthDirs = monthDirInfo.EnumerateDirectories()
    .OrderBy(d => d.CreationTime);

I have used EnumerateDirectories because it is more efficient. GetDirectories would collect all directories first before it would begin ordering them.

like image 108
Tim Schmelter Avatar answered Jan 12 '23 08:01

Tim Schmelter