gpt4 book ai didi

c# - 如何对使用 Directoryinfo 读取的文件名进行排序

转载 作者:行者123 更新时间:2023-11-30 17:00:34 24 4
gpt4 key购买 nike

我想阅读文件夹和文件名,它们被放入一个列表中,并排序显示例如,我有一个如下所示的文件:

1-4999.txt

5000-9999.txt……

我想对数据文件夹进行排序

       var endpageNext = pagenumber * 100;
var startpageNext = endpageNext - (100 - 1);

var lst = GetFile(startpageNext, endpageNext);

Picture Data Folder

Picture Visual Studio break point

        internal List<string> GetFile(int startpagenext, int endpagenext)
{
var dir = DataAccessSetting.CustomerSplit;
DirectoryInfo directoryInfo = new DirectoryInfo(dir);
var s = directoryInfo.GetFiles("*.txt");
var lstfilename = new List<string>();
foreach (var file in s)
{
var fileWithoutExtension = Path.GetFileNameWithoutExtension(file.Name);
var splitNameFile = fileWithoutExtension.Split('-');

if ((startpagenext >= int.Parse(splitNameFile[0]) && startpagenext <= int.Parse(splitNameFile[1])) || (endpagenext >= int.Parse(splitNameFile[0]) && endpagenext <= int.Parse(splitNameFile[1])))
{
var ppath = dir + fileWithoutExtension + ".txt";
lstfilename.Add(ppath);
}

}

return lstfilename;
}

最佳答案

这应该有效:

List<string> lstfilename = System.IO.Directory
.EnumerateFiles(dir, "*.txt", System.IO.SearchOption.TopDirectoryOnly)
.Select(Path => new {
Path,
split = System.IO.Path.GetFileNameWithoutExtension(Path).Split('-')
})
.Where(x => x.split.Length == 2 && x.split.All(s => s.All(Char.IsDigit)))
.Select(x => new {
x.Path,
Num1 = int.Parse(x.split[0]),
Num2 = int.Parse(x.split[1]),
})
.Where(x => (startpagenext >= x.Num1 && startpagenext <= x.Num2)
|| (endpagenext >= x.Num1 && endpagenext <= x.Num2))
.OrderBy(x => x.Num1).ThenBy(x => x.Num2)
.Select(x => x.Path)
.ToList();

关于c# - 如何对使用 Directoryinfo 读取的文件名进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22017778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com