C # Sorting directory names using LINQ

I found something similar here , but couldn't get it to work. I am very new to LINQ and therefore not quite sure what is happening to him. Any help would be greatly appreciated. I have directory names, for example:

directory-1 article-about-something-else 

I want to sort them by name, but so far have failed. They are located on a network drive located on the RedHat server. The directory listing goes into a distorted mess in seemingly random order.

Here is what I 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. At the moment, I'm a little confused. I am sure that I also have something obvious.

+4
source share
3 answers

You order by the name of the root folder instead of the name of each subdirectory.

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 used EnumerateDirectories because it is more efficient. GetDirectories collected all directories before it began to organize them.

+5
source
 dirInfo.GetDirectories().OrderBy(d => d.Name); 
+3
source
 var dirs = dirInfo.GetDirectories().OrderBy(d => d.Name); 

LINQ is the creation of "functions" on the fly ... So, you are creating a function here that takes a variable "d" representing the current record and returns d.Name for sorting.

+2
source

Source: https://habr.com/ru/post/1487503/


All Articles