c# - foreach 按文件索引顺序遍历文件(file1.png、file2.png、file10.png)

标签 c# foreach natural-sort

<分区>

这是我的代码:

private void Method1()
{
    int i = 1;
    foreach (string file in Directory.EnumerateFiles(ImagesPath))
    {
        if (Path.GetExtension(file).EndsWith(".png"))
        {
            string image = (Path.GetFullPath(file));
            i += 1;                
        }
    }
}

imagesPath 是一个绑定(bind)到包含图像的文件夹的字符串,

Image1.png,
Image2.png
.
.
.
.
Image10.png,
Image11.png
.
.

我想从 Image1.png--->Image2.png 迭代,但是 foreach 迭代 Image1.png-->Image10.png-->Image11.png 等等。

有什么方法可以覆盖它吗?

最佳答案

您需要去除“图像”前缀和“.png”后缀,将剩下的转换为整数并对其进行排序。例如:

var orderedFiles = Directory
    .EnumerateFiles(ImagesPath)
    //Remove "image" and ".png" and convert the rest to an integer
    .Select(f => int.Parse(f.Replace("image", "").Replace(".png", ""))
    //Order the resultnumerically
    .OrderBy(num => num)
    //Add the "image" prefix and ".png" suffix back in
    .Select(num => string.Format("image{0}.png", num));

foreach(string file in orderedFiles)
{
    //...
}

此外,您的目录似乎包含非 PNG 文件。不要在循环中使用 if,只需过滤 Directory.EnumerateFiles 中的结果即可方法:

Directory.EnumerateFiles(ImagesPath, "*.png")

关于c# - foreach 按文件索引顺序遍历文件(file1.png、file2.png、file10.png),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33746956/

相关文章:

sql - PostgreSQL ORDER BY 问题 - 自然排序

c# - C# 计算两个日期之间的工作日数

c# - 将 system.array 对象转换为 int[] 字符串或其他类型的对象

c# - 解码查询参数值中带有特殊和或 + 字符的 Url

c# - 简化任务 foreach 循环 c#

php - sql排序数字然后按字母顺序

c# - 如何在 C# 中获取调用函数的名称?

php - 如何从 PHP 中的数组中获取字符串 (Foreach)

php - 从最高到最低相似度回显字符串

perl - 对键包含非字母数字字符的哈希进行排序