I am having 4 strings:
"h:/a/b/c"
"h:/a/b/d"
"h:/a/b/e"
"h:/a/c"
I want to find the common prefix for those strings, i.e. "h:/a"
.
How to find that?
Usually I'd split the string with delimiter '/'
and put it in another list, and so on.
Is there any better way to do it?
string[] xs = new[] { "h:/a/b/c", "h:/a/b/d", "h:/a/b/e", "h:/a/c" };
string x = string.Join("/", xs.Select(s => s.Split('/').AsEnumerable())
.Transpose()
.TakeWhile(s => s.All(d => d == s.First()))
.Select(s => s.First()));
with
public static IEnumerable<IEnumerable<T>> Transpose<T>(
this IEnumerable<IEnumerable<T>> source)
{
var enumerators = source.Select(e => e.GetEnumerator()).ToArray();
try
{
while (enumerators.All(e => e.MoveNext()))
{
yield return enumerators.Select(e => e.Current).ToArray();
}
}
finally
{
Array.ForEach(enumerators, e => e.Dispose());
}
}