[英]Linq to get distinct subdirectories from list of paths
我正在尝试在C#中为项目创建文件目录浏览器。
我从当前路径开始(对于这个例子,它将是'/')。
从我有的路径列表
示例:/ a / b,/ a / bb,/ a / bbb,/ b / a,/ b / aa,/ b / aaa,/ c / d,/ d / e
我想返回一个不同的子目录列表
预期回报:/ a /,/ b /,/ c /,/ d /
如何使用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();
结果将是到各个直接子目录的路径数组(示例):
假设您有一个名为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);
}
您可以使用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();
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.