Linq从路径列表中获取不同的子目录

本文关键字:子目录 获取 路径 列表 Linq | 更新日期: 2023-09-27 17:58:26

我正试图用C#为一个项目制作一个文件目录浏览器。

我从当前路径开始(对于本例,它将是"/")。

从我有的路径列表

示例:/a/b、/a/bb、/a/bbb、/b/a、/b/aa、/b/aaa、/c/d、/d/e

我想返回一个不同子目录的列表

预期回报:/a/,/b/,/c/,/d/

如何使用LINQ来实现这一点?

Linq从路径列表中获取不同的子目录

我认为这几乎涵盖了它。示例控制台应用程序:

public static void Main()
{
    string[] paths = new[] { "/a/b", "/a/bb", "/a/bbb", "/b/a", "/b/aa", "/b/aaa", "/c/d", "/d/e" }; 
    string root = "/";
    Console.WriteLine(string.Join(", ", paths.Select(s => GetSubdirectory(root, s)).Where(s => s != null).Distinct()));
}
static string GetSubdirectory(string root, string path)
{
    string subDirectory = null;
    int index = path.IndexOf(root);
    Console.WriteLine(index);
    if (root != path && index == 0)
    {
        subDirectory = path.Substring(root.Length, path.Length - root.Length).Trim('/').Split('/')[0];
    }
    return subDirectory;
}

参见小提琴:http://dotnetfiddle.net/SXAqxY

示例输入:"/"
样本输出:a、b、c、d

示例输入:"/a"
样本输出:b,bb,bbb

我可能没有抓住要点,但像这样的东西不是你想要的吗?

var startingPath = @"c:'";
var directoryInfo = new DirectoryInfo(startingPath);
var result = directoryInfo.GetDirectories().Select(x => x.FullName).ToArray();

结果将是到各种直接子目录的路径阵列(例如):

  1. "c:''Boot"
  2. "c:''Temp"
  3. 等等
void Main()
{
  string [] paths = {  @"/a/b", @"/a/bb", @"/a/bbb", @"/b/a", @"/b/aa", @"/b/aaa", @"/c/d", @"/d/e" };
  var result = paths.Select(x => x.Split('/')[1]).Distinct();
  result.Dump();
}

如果你不知道你是否有一个领先的/,那么使用这个:

var result = paths.Select(x =>x.Split(new string [] {"/"},
                                        StringSplitOptions.RemoveEmptyEntries)[0])
                  .Distinct();

您可以使用Path.GetPathRoot

var rootList = new List <string>();
foreach (var fullPath in myPaths)
{
    rootList.Add(Path.GetPathRoot(fullPath))
}
return rootList.Distinct();

或者:

myPaths.Select(x => Path.GetPathRoot(x)).Distinct();

或者使用Directory.GetDirectoryRoot:

myPaths.Select(x => Directory.GetDirectoryRoot(x)).Distinct();

编辑

如果你想要N+1路径,你可以做:

string dir = @"C:'Level1'Level2;  
string root = Path.GetPathRoot(dir);
string pathWithoutRoot = dir.Substring(root.Length);       
string firstDir = pathWithoutRoot.Split(Path.DirectorySeparatorChar).First();

假设您有一个名为paths的路径列表,您可以执行以下操作:

string currentDirectory = "/";
var distinctDirectories = paths.Where(p => p.StartsWith(currentDirectory)
                               .Select(p => GetFirstSubDir(p, currentDirectory)).Distinct();

...

string GetFirstSubDir(string path, string currentDirectory)
{
    int index = path.IndexOf('/', currentDirectory.Length);
    if (index >= 0)
        return path.SubString(currentDirectory.Length - 1, index + 1 - currentDirectory.Length);
    return path.SubString(currentDirectory.Length - 1);
}