我得到了文件和目录的列表List<string> pathes
。现在我想计算每条路径相互共享的最深公共分支。
我们可以假设它们都共享一条共同的路径,但这在开始时是未知的。
假设我有以下三个条目:
- C:/Hello/World/This/Is/An/Example/Bla.cs
- C:/Hello/World/This/Is/Not/An/Example/
- C:/你好/地球/Bla/Bla/Bla
这应该得到结果: C:/Hello/ 因为 Earth 正在打破这个子目录的“链”。
第二个例子:
- C:/Hello/World/This/Is/An/Example/Bla.cs
- C:/Hello/World/This/Is/Not/An/Example/
-> C:/你好/世界/这/是/
你将如何进行?我尝试使用 string.split(@"/") 并从第一个字符串开始并检查该数组的每个部分是否包含在其他字符串中。但是,这将是一个非常昂贵的调用,因为我正在迭代 (list_of_entries)^list_of_entries。有没有更好的解决方案?
我当前的尝试将类似于以下内容(C# + LINQ):
public string CalculateCommonPath(IEnumerable<string> paths)
{
int minSlash = int.MaxValue;
string minPath = null;
foreach (var path in paths)
{
int splits = path.Split('\\').Count();
if (minSlash > splits)
{
minSlash = splits;
minPath = path;
}
}
if (minPath != null)
{
string[] splits = minPath.Split('\\');
for (int i = 0; i < minSlash; i++)
{
if (paths.Any(x => !x.StartsWith(splits[i])))
{
return i >= 0 ? splits.Take(i).ToString() : "";
}
}
}
return minPath;
}