【问题标题】:Get List of Files sorted by name from directory从目录中获取按名称排序的文件列表
【发布时间】:2014-10-01 14:50:55
【问题描述】:

我需要从目录中获取按名称排序的文件列表。

我的文件被命名为:

TestFile_1.xml,
TestFile_2.xml
TestFile_3.xml
.
.
TestFile_10.xml
TestFile_11.xml

我使用下面的sn-p进行排序

DirectoryInfo di = new DirectoryInfo(jsonFileInfo.FolderPath);
FileSystemInfo[] files = di.GetFileSystemInfos();
var orderedFiles = files.OrderBy(f => f.Name);`

有了这个片段,我得到的结果是

TestFile_1.xml,
TestFile_10.xml
TestFile_11.xml
.
.
TestFile_2.xml
TestFile_3.xml
.
.

如何排序?

【问题讨论】:

  • 已经可以了。否则,您应该澄清要求。名称是字符串,字符串不知道10 比“2”“大”。
  • 简单解决方案:将文件命名为TestFile_01 而不是TestFile_1
  • 我无法将文件从 TestFile_1 重命名为 TestFile_01。文件名将始终保持为TestFile1
  • 文件都是以TestFile_开头的吗?
  • 你所有的文件都遵循 TestFile_[number].xml 模式?

标签: c# file sorting directory


【解决方案1】:

名称是一个字符串,"10"大于“2”。如果要按下划线后面的数字排序:

var orderedFiles = files
    .Select(f => new{ 
        File = f, 
        NumberPart = f.Name.Substring(f.Name.IndexOf("_") + 1)
    })
    .Where(x => x.NumberPart.All(Char.IsDigit))
    .Select(x => new { x.File, Number = int.Parse(x.NumberPart) })
    .OrderBy(x => x.Number)
    .Select(x => x.File);

如果您想包含所有不以数字结尾的文件,则应先包含这些文件:

orderedFiles = files
    .Select(f => new
    {
        File = f,
        NumberPart = f.Name.Substring(f.Name.IndexOf("_") + 1)
    })
    .Select(x => new { x.File, x.NumberPart, AllDigit = x.NumberPart.All(Char.IsDigit) })
    .Select(x => new
    {
        x.File,
        Number = x.AllDigit ? int.Parse(x.NumberPart) : (int?)null
    })
    .OrderBy(x => x.Number.HasValue)
    .ThenBy(x => x.Number ?? 0)
    .Select(x => x.File);

如果您甚至希望静态文件名始终位于顶部(如注释所示),您可以使用:

....
.OrderByDescending(x => x.File.Name.Equals("TestFile_cover.xml", StringComparison.CurrentCultureIgnoreCase))
.ThenBy(x => x.Number.HasValue)
.ThenBy(x => x.Number ?? 0)
.Select(x => x.File);

【讨论】:

  • 如果我的所有文件都遵循模式 TestFile_[number].xml 但并非所有文件都遵循模式 TestFile_[number].xml,则此方法很好,列表的第一个文件应始终为 TestFile_cover.xml
猜你喜欢
  • 2011-10-20
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多