【问题标题】:Enumerate Files Ordered by Numbered Filename C#枚举按编号文件名排序的文件 C#
【发布时间】:2016-04-12 12:15:28
【问题描述】:

我在订购文件时遇到了一点问题,我研究了堆栈溢出并尝试了所有其他方法,但我一直遇到同样的问题

这是我的代码:

public static List<Bitmap> CogerFotosAlamacenadas()
    {
        List<Bitmap> Lista = new List<Bitmap>();
        DirectoryInfo Directorio = new DirectoryInfo(Environment.CurrentDirectory + "\\Almacenamiento");
        FileInfo[] ListaDeFotos = Directorio.GetFiles("*.bmp");

        Array.Sort(ListaDeFotos, delegate (FileInfo x, FileInfo y)
        {
            return string.Compare(x.Name, y.Name);
        });

        foreach (FileInfo foto in ListaDeFotos)
        {
            Image PlaceHolder = Image.FromFile(foto.FullName);

            Lista.Add((Bitmap)PlaceHolder);

        }


        return Lista;
    }

我有一系列照片,命名为:“Foto”+numberFrom0To300+“bmp”;

应用此代码后,我的列表将得到按 0_10_100_101_102 排序的照片...

已经尝试过 .GetFiles() 的默认顺序 这段代码和另一个在堆栈溢出中找到的代码,但没有使用 array.sort 我总是得到相同的结果帽子奇数订单号

但我必须不惜一切代价订购它们 0,1,2,3,4...

有人知道如何控制它吗?

【问题讨论】:

  • 你必须更清楚:问题是什么?它做错了什么?
  • "应用此代码后,我的列表将得到按 0_10_100_101_102 排序的照片..." "但我必须不惜一切代价订购它们 0,1,2,3,4..." i认为它足够清楚,不会立即被否决
  • 我让你澄清不要引用你的问题。
  • 我不会说英语,所以也许我解释得不够好,问题是我的程序认为 photo101.bmp 比 photo2.bmp 小,我不希望他们像这样订购我想要他们订购 1,2,3,4,5 而不是 1,10,100,101 等等

标签: c#


【解决方案1】:

您正在比较使用lexicographical order 的字符串,您想按数字排序。然后你必须总是解析相关的子字符串。您可以使用 LINQ:

FileInfo[] orderedPhotos = Directorio.EnumerateFiles("*.bmp")
    .Where(f => f.Name.Length > "Foto.bmp".Length)
    .Select(f => new { 
        File = f, 
        Number = System.IO.Path.GetFileNameWithoutExtension(f.Name).Substring("Foto".Length)
    })
    .Where(x => x.Number.All(Char.IsDigit))
    .Select(x => new { 
        x.File, 
        Integer = int.Parse(x.Number)
    })
    .OrderBy(x => x.Integer)
    .Select(x => x.File)
    .ToArray();

【讨论】:

  • 经过测试且工作正常,物品按我的意愿订购
  • @ElanSanchezOrtiz:不客气。如果您想反转顺序,请使用OrderByDescending。如果您想搜索具有给定数字(或范围)的照片,请使用 Where(x =&gt; x.Integer == 123)
【解决方案2】:

快速(但可能是 dirty - interop 需要)解决方案是以不同的方式排序:

using System.Runtime.InteropServices;
...

[DllImport("shlwapi.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern int StrCmpLogicalW(string x, string y);

...

// change your current Array.Sort to this one
Array.Sort(ListaDeFotos, (left, right) => StrCmpLogicalW(left.Name, right.Name));

诀窍在于,string.Compare 以 字典顺序 方式进行比较(因此 "10" &lt; "9")StrCmpLogicalW 提供一种 逻辑 排序 ("10" &gt; "9")

【讨论】:

  • 感谢您的回答!使用了另一个答案,因为它不必导入并且对我来说更容易,但非常感谢!可能对其他人有用!
猜你喜欢
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
  • 2020-03-24
  • 1970-01-01
  • 2012-04-09
  • 2022-01-27
  • 2013-05-30
相关资源
最近更新 更多