5

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.

Community
  • 1
  • 1
ahwm
  • 672
  • 9
  • 23

3 Answers3

5

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.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
3
dirInfo.GetDirectories().OrderBy(d => d.Name);
Patrick Magee
  • 2,951
  • 3
  • 33
  • 50
2
var dirs = dirInfo.GetDirectories().OrderBy(d => d.Name);

LINQ is about creating "functions" on the fly... So you're creating a function here that takes in a variable called "d" representing the current record and returns d.Name to sort.

Haney
  • 32,775
  • 8
  • 59
  • 68