目录中的文件按fileName升序排序 [英] Files in directory sort by fileName ascending

查看:150
本文介绍了目录中的文件按fileName升序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having a list of files from a directory and I want to sort it out by filename.

这是主要代码:

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);
    }
}

这是存储所有文件的Picture类:

here is the class Picture where all the files are stored:

public class Picture
{
    public string ImagePath { get; set; }
    public string FileName { get; set; }
    public DateTime CreationDate { get; set; }
}

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

How do you do to sort a files list by order of FileName?

推荐答案

只需更改您的for循环:

Simply change your for loop :

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

}

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

Alternatively, you can rewrite the whole loop using this code :

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);

这篇关于目录中的文件按fileName升序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆