我使用此代码进行排序:
var fileEntries = from f in Directory.GetFiles(Application.StartupPath + "/TrainedFaces/", "*.bmp", SearchOption.AllDirectories)
let fi = new FileInfo(f)
orderby fi.Name
select fi.FullName;
有一些问题当我把Face10,Face11首先拿到face1之后拿到Face10所以这就是问题
这是我想要的输出
[0] = "N:\FaceRecProOV - Copy (2)\FaceRecProOV\bin\Debug/TrainedFace/1\ 1.bmp"
[1] = "N:\FaceRecProOV - Copy (2)\FaceRecProOV\bin\Debug/TrainedFaces/2\ 2.bmp"
[2] = "N:\FaceRecProOV - Copy (2)\FaceRecProOV\bin\Debug/TrainedFaces/3\ 3.bmp"
[3] = "N:\FaceRecProOV - Copy (2)\FaceRecProOV\bin\Debug/TrainedFaces/4\ 4.bmp"
[4] = "N:\FaceRecProOV - Copy (2)\FaceRecProOV\bin\Debug/TrainedFaces/4\ 9.bmp"
[5] = "N:\FaceRecProOV - Copy (2)\FaceRecProOV\bin\Debug/TrainedFaces/4\ 10.bmp"
但它给出了
[0] = "N:\FaceRecProOV - Copy (2)\FaceRecProOV\bin\Debug/TrainedFace/1\ 1.bmp"
[5] = "N:\FaceRecProOV - Copy (2)\FaceRecProOV\bin\Debug/TrainedFaces/4\ 10.bmp"
[1] = "N:\FaceRecProOV - Copy (2)\FaceRecProOV\bin\Debug/TrainedFaces/2\ 2.bmp"
守则有什么问题???
答案 0 :(得分:2)
这样做是因为它正在对它进行排序,假设它是一个字符串(“10”出现在“2”之前)。
您必须获取文件名并将其转换为int并根据它进行排序。
答案 1 :(得分:1)
您按字母顺序排序数据,而不是数字排序。假设根本无法修改输入,则需要将文件名解析为数字,然后对其进行排序。
var fileEntries = from f in Directory.GetFiles(Application.StartupPath + "/TrainedFaces/", "*.bmp", SearchOption.AllDirectories)
let fi = new FileInfo(f)
orderby parse(fi.Name )
select fi.FullName;
public static int Parse(string filename)
{
//for your real program you'll want to ensure that there is error handling and determine what to do with non-numeric filenames.
return int.Parse(filename.Substring(0, filename.LastIndexOf('.'));
}
答案 2 :(得分:1)
var fileEntries = Directory.GetFiles(Application.StartupPath + "/TrainedFaces/", "*.bmp", SearchOption.AllDirectories)
.Select(f=>new FileInfo(f))
.OrderNaturallyBy(fi=>fi.Name)
.Select(fi=>fi.FullName);
public static class S_O_Extensions
{
public static IEnumerable<T> OrderNaturallyBy<T>(this IEnumerable<T> list, Func<T,string> selector)
{
return list.Select(item => new
{
t = item,
tempstr = Regex.Replace(selector(item), @"\d+", m => m.Value.PadLeft(20, '0'))
})
.OrderBy(x => x.tempstr)
.Select(x => x.t);
}
}