简体   繁体   English

C#使用LINQ对目录名称进行排序

[英]C# Sorting Directory Names using LINQ

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. 我对LINQ很新,所以不完全确定它是怎么回事。 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. 它们位于RedHat服务器上的网络驱动器上。 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. 我确信我也遗漏了一些明显的东西。

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. 我使用了EnumerateDirectories因为它效率更高。 GetDirectories would collect all directories first before it would begin ordering them. GetDirectories会在开始排序之前先收集所有目录。

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

LINQ是关于动态创建“函数”的......所以你在这里创建一个函数,它接受一个名为“d”的变量来表示当前记录并返回d.Name来排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM