按数字顺序将文件夹中的所有图像列出到列表 [英] List all images from a folder to a List in Numerical order
问题描述
我有一个文件夹C:\Images \包含12个图像。我使用下面的代码从文件夹中提取所有图像并显示在文件列表中。但是图像的顺序不正确。
DirectoryInfo dir = new DirectoryInfo((strImagePaths));
FileInfo [] file = dir.GetFiles();
显示为Img1,img10,img11,img12,img2,img3, img4,img5,img6,img7,ing8,img9通过某种排序
但我需要按照数字顺序显示img1,2,3,4,5 ,6,7,8,9,10,11,12
提前致谢
I have a folder C:\Images\ contains 12 Images.I have use the below code to extract all the images from the folder and display in file list. But the images are not in the proper order.
DirectoryInfo dir = new DirectoryInfo((strImagePaths));
FileInfo[] file = dir.GetFiles();
Its displaying as Img1,img10,img11,img12,img2,img3,img4,img5,img6,img7,ing8,img9 by some kind of sorting
But i need to display in numerical order like img1,2,3,4,5,6,7,8,9,10,11,12
Thanks in advance
推荐答案
您需要一个自然的排序顺序。试试这个解决方案:
http://www.interact-sw.co.uk/iangblog/2007/12/13/natural-sorting
You need a natural sort order. Try this solution:
http://www.interact-sw.co.uk/iangblog/2007/12/13/natural-sorting
以下是使用通用集合的替代解决方案
Here is an alternative solution using a generic collection
// Create a sorted list where the key will be a string = adjusted filename, value = the original FileInfo
var sl = new System.Collections.Generic.SortedList<string, FileInfo>();
foreach (var f in file)
{
// Get the name
var jpgName = f.Name;
// find the number
var resultString = System.Text.RegularExpressions.Regex.Match(jpgName, @"\d+").Value;
//Make sure we have a number
int res;
if(int.TryParse(resultString, out res))
{
// Convert the filename we will use as a key - you might need more zeroes if you have a lot of files
jpgName = String.Format("{0}{1}", jpgName.Replace(resultString, ""), res.ToString("0000000"));
}
sl.Add(jpgName, f);
}
// Sorted list sl now contains the files in the natural sort order
您可以按照以下方式执行
you can do as below
List<string> Msilist = Directory.GetFiles(strImagePaths, "*.Jpeg")
.Select(path => Path.GetFileNameWithoutExtension(path))
.OrderBy(x => int.Parse(x.TrimStart("image".ToArray()))).ToList();
请注意您需要按文件名的编号部分订购
note that you need to order by number part of the file name
这篇关于按数字顺序将文件夹中的所有图像列出到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!