Reputation: 9435
I'm getting the files from the Directory in asp.net using c# languages:
string[] array=Directory.GetFiles(Server.MapPath("Image"));
My Image folder has images like Image1.jpg, Image2.jpg, Image3.jpg........Image100.jpg.
My Issue is, I'm not getting the image files in order. How do I get the Image files in order say Image1 to Image100....
yea...I solved it myself..Here is the Solution:
var arr = (from u in Directory.GetFiles(Server.MapPath("Images")) let fi = new FileInfo(u) orderby fi.CreationTime select u);
Upvotes: 1
Views: 2312
Reputation: 761
This will work
List<string> s = new List<string>();
s.Add("image1.jpg");
s.Add("image10.jpg");
s.Add("image3.jpg");
s.Add("image45.jpg");
List<string> lst = s.OrderBy(x => int.Parse(x.Split('.')[0].Split(new string[] { "image" }, StringSplitOptions.None)[1])).ToList();
Upvotes: 0
Reputation: 648
you can use linq like this:
Directory.GetFiles(Server.MapPath("Image")).OrderBy(c => c.Name).ToList();
Upvotes: 1
Reputation: 98750
Try like this;
var images = from img in Directory.GetFiles(Server.MapPath("Image"))
orderby img descending
select img;
Or as an alternative, you can use OrderByDescending
;
var images = Directory.EnumerateFiles(Server.MapPath("Image"))
.OrderByDescending(img => img);
Upvotes: 2
Reputation: 125630
Using LINQ OrderBy
:
string[] array = Directory.GetFiles(Server.MapPath("Image"))
.OrderBy(x => x)
.ToArray();
or without LINQ, using Array.Sort
method:
string[] array = Directory.GetFiles(Server.MapPath("Image"));
Array.Sort(array);
But it will sort using default string comparison, so Image100
will be before Image2
.
It will be a bit more tricky to sort it using the number only, but you can do it with linq:
string[] array = (from f in Directory.GetFiles(Server.MapPath("Image"))
let n = int.Parse(f.Replace("Image", string.Empty).Replace(".jpg", string.Empty))
order by n
select f).ToArray();
Upvotes: 2