繁体   English   中英

如何对目录显示在硬盘上的目录进行排序?

[英]How can i sort the directories as they appear on my hard disk?

例如,在我的硬盘上:

dir1 dir2 dir3 dir4 .....

我的代码是:

DirectoryInfo dInfo = new DirectoryInfo(AutomaticsubDirectoryName);
DirectoryInfo[] subdirs = dInfo.GetDirectories();

所以在subdirs我得到了所有目录,但它们的顺序与我的硬盘上的顺序不同。 我如何对它们进行排序,以便它们以与硬盘上相同的顺序位于subdirs中?


解决此问题:

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();

工作完美。

假设您正在谈论文件系统以及Windows Explorer之类的软件如何显示名称,我想您正在谈论对名称进行自然排序。 在这里阅读: 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();

Windows使用的字符串比较功能可供所有人使用。 因此,您将需要一点点拼音才能获得与资源管理器使用的排序顺序完全相同的排序顺序。 将其包装在IComparer <>中,因此您可以将其传递给Array.Sort()或OrderBy()Linq子句:

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);
}

解决此问题:

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();

工作完美。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM