I have a list of files and directories List<string> pathes . Now I would like to calculate the deepest common branch, each of which shares with each other.
We can assume that they all have a common path, but this is unknown at the beginning.
Let's say I have the following three entries:
- C: /Hello/World/This/Is/An/Example/Bla.cs
- C: / Hello / World / This / Is / Not / Ap / Example /
- C: / Hello / Earth / Bla / Bla / Bla
This should get the result: C: / Hello /, since Earth destroys this "chain" of subdirectories.
Second example:
- C: /Hello/World/This/Is/An/Example/Bla.cs
- C: / Hello / World / This / Is / Not / Ap / Example /
-> C: / Hello / World / This / Is /
What will you do? I tried to use string.split (@ "/") and start from the first line and check if each part of this array is contained in other lines. However, this will be a very expensive call as I repeat (list_of_entries) ^ list_of_entries. Is there a better solution?
My current attempt will be similar to the following (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; }
string c # url utility-method
Frame91
source share