On my hard disk i have for example:
dir1 dir2 dir3 dir4 .....
My code is :
DirectoryInfo dInfo = new DirectoryInfo(AutomaticsubDirectoryName);
DirectoryInfo[] subdirs = dInfo.GetDirectories();
so in subdirs
i'm getting all the directories but they are not in the same order as they are on my hard disk. How can i sort them so they will be in subdirs
in the same order they are on my hard disk ?
Solved it by this:
DirectoryInfo[] subdirs = dInfo.GetDirectories().OrderBy(d =>
{
int i = 0;
if (d.Name.Contains("Lightning ") && d.Name.Contains(" Length") && d.Name.IndexOf("Lightning ") < d.Name.IndexOf(" Length"))
{
string z = d.Name.Substring(("Lightning ").Length);
string f = z.Substring(0, z.IndexOf(" Length"));
if (Int32.TryParse(f, out i))
return i;
else
return -1;
}
else
return -1;
}).ToArray();
Working perfect.
Assuming you are talking about filesystems and how a software like Windows Explorer displays the names, I suppose you are talking about natural sorting the names. Read here: http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html
Craetion time
是合理的标准,它们如何出现在硬盘上。
DirectoryInfo[] subdirs = dInfo.GetDirectories().OrderBy(d => d.CreationTime).ToArray();
The string compare function that Windows uses is exposed for everybody to use. So you'll need a wee bit of pinvoke to get the exact same sort order as Explorer uses. Wrapping it in an IComparer<> so you can just pass it to Array.Sort() or an OrderBy() Linq clause:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
public class LogicalComparer : IComparer<string> {
public int Compare(string x, string y) {
return StrCmpLogicalW(x, y);
}
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern int StrCmpLogicalW(string s1, string s2);
}
Solved it by this:
DirectoryInfo[] subdirs = dInfo.GetDirectories().OrderBy(d =>
{
int i = 0;
if (d.Name.Contains("Lightning ") && d.Name.Contains(" Length") && d.Name.IndexOf("Lightning ") < d.Name.IndexOf(" Length"))
{
string z = d.Name.Substring(("Lightning ").Length);
string f = z.Substring(0, z.IndexOf(" Length"));
if (Int32.TryParse(f, out i))
return i;
else
return -1;
}
else
return -1;
}).ToArray();
Working perfect.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.