繁体   English   中英

如何在C#中按名称对目录中的PDF文件进行数字排序

[英]How to sort PDF files in a directory in numerical order by its name in c#

这是我尝试过的:

var vv = new DirectoryInfo(@"C:\Image").GetFileSystemInfos("*.bmp").OrderBy(fs=>int.Parse(fs.Name.Split('_')[1].Substring(0, fs.Name.Split('_')[1].Length - fs.Extension.Length)));

我建议您创建一个自定义排序器类,该类实现IComparer接口以对FileSystemInfo数组进行排序。

是的,它不像使用LINQ那样性感,但是很干净

        DirectoryInfo di = new DirectoryInfo("C:\\Image");
        FileSystemInfo[] fi = di.GetFileSystemInfos("*.bmp");

        Array.Sort(fi, new SortByNum());

public class SortByNum : IComparer<FileSystemInfo>
{
    public int Compare( FileSystemInfo x, FileSystemInfo y)
    {
        // extract the numeric portion of the file name
        int val_x = int.Parse(x.Name.Split('_')[1].Substring(0, x.Name.Split('_')[1].Length - x.Extension.Length));
        int val_y = int.Parse(y.Name.Split('_')[1].Substring(0, y.Name.Split('_')[1].Length - y.Extension.Length));

        return val_x.CompareTo(val_y);
    }
}

暂无
暂无

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

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