目录中的文件按fileName升序排序

dtj*_*msy 3 .net c# linq sql-order-by

我有一个目录中的文件列表,我想按文件名排序.

这是主要代码:

var localPath = this.Server.MapPath("~/Content/Img/" + type + "/");
var directory = new DirectoryInfo(localPath);
isDirectory = directory.Exists;

if (isDirectory)
{
    foreach (FileInfo f in directory.GetFiles())
    {
        Picture picture = new Picture();

        picture.ImagePath = path;
        picture.CreationDate = f.CreationTime;
        picture.FileName = f.Name;
        listPictures.Add(picture);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是存储所有文件的类图片:

public class Picture
{
    public string ImagePath { get; set; }
    public string FileName { get; set; }
    public DateTime CreationDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如何按FileName的顺序对文件列表进行排序?

Ste*_*e B 9

只需更改你的for循环:

foreach (FileInfo f in directory.GetFiles().OrderBy(fi=>fi.FileName))
{

}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用以下代码重写整个循环:

var sortedFiles = from fi in directory.GetFiles()
                  order by fi.FileName
                  select new Picture { ImagePath = path, CreationDate = f.CreationTime, FileName = f.FileName };

listPictures.AddRange(sortedFiles);
Run Code Online (Sandbox Code Playgroud)