我有点麻烦订购我的文件,我研究了堆栈溢出并尝试了所有其他方法,但我一直遇到同样的问题
这是我的代码:
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()的默认订单 这个代码和另一个在堆栈溢出whitout中使用array.sort 我总是得到相同的结果帽奇数订单号
但我必须不惜一切代价订购0,1,2,3,4 ......
是不是有人知道如何控制它?
答案 0 :(得分:1)
快速(但可能脏 - interop 需要)解决方案是以不同方式排序:
*ngFor
当div
提供一种逻辑时,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
)进行比较sort("10" < "9"
)
答案 1 :(得分: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();