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.

3
  • I'll give a try, but that hasn't worked either when I used f => f.Name Commented Jun 21, 2013 at 15:46
  • 1
    Two things... monthDirInfo should be exactly the same as dir so why create a new object? Also Sayse is correct you need to use d => d.Name. Commented Jun 21, 2013 at 15:46
  • I knew I was missing something obvious. Thanks guys! :) Commented Jun 21, 2013 at 15:51

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Erm.. that would be d.name or n => n.Name surely?
3
dirInfo.GetDirectories().OrderBy(d => d.Name);

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.