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

时间:2014-04-15 22:39:34

标签: c# linq list distinct

我正在尝试在C#中为项目创建文件目录浏览器。

我从当前路径开始(对于此示例,它将是' /')。

从我拥有的路径列表中

  

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

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

  

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

如何使用LINQ来实现这一目标?

5 个答案:

答案 0 :(得分:2)

我认为这只是涵盖它。示例控制台应用程序:

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

答案 1 :(得分:1)

我可能会忽略这一点,但是这样的东西不会是你想要的吗?

var startingPath = @"c:\";

var directoryInfo = new DirectoryInfo(startingPath);

var result = directoryInfo.GetDirectories().Select(x => x.FullName).ToArray();

结果将是到各个直接子目录的路径数组(示例):

  1. “C:\引导”
  2. “C:\ TEMP”

答案 2 :(得分:0)

假设您有一个名为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);
}

答案 3 :(得分:0)

您可以使用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();

答案 4 :(得分:0)

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