有没有一种简单的方法可以在 C# 中组合两个相对路径? [英] Is there an easy method to combine two relative paths in C#?

查看:53
本文介绍了有没有一种简单的方法可以在 C# 中组合两个相对路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 C# 中组合两个相对路径.

I want to combine two relative paths in C#.

例如:

string path1 = "/System/Configuration/Panels/Alpha";
string path2 = "Panels/Alpha/Data";

我想回来

string result = "/System/Configuration/Panels/Alpha/Data";

我可以通过拆分第二个数组并在 for 循环中进行比较来实现这一点,但我想知道是否有类似于 Path.Combine 的东西可用,或者是否可以使用正则表达式或林克?

I can implement this by splitting the second array and compare it in a for loop but I was wondering if there is something similar to Path.Combine available or if this can be accomplished with regular expressions or Linq?

谢谢

推荐答案

假设这两个字符串的格式始终与您的示例中的格式相同,这应该有效:

Provided that the two strings are always in the same format as in your example, this should work:

string path1 = "/System/Configuration/Panels/Alpha";
string path2 = "Panels/Alpha/Data";

var x = path1.Split('/');
var y = path2.Split('/');

string result = Enumerable.Range(0, x.Count())

                          .Where(i => x.Skip(i)
                                       .SequenceEqual(y.Take(x.Skip(i)
                                                              .Count())))

                          .Select(i => string.Join("/", x.Take(i)
                                                         .Concat(y)))

                          .LastOrDefault();

// result == "/System/Configuration/Panels/Alpha/Data"

<小时>

对于 path1 = "/System/a/b/a/b"path2 = "a/b/a/b/c" 结果是 <代码>"/System/a/b/a/b/a/b/c".您可以将 LastOrDefault 更改为 FirstOrDefault 以获取 "/System/a/b/a/b/c".


For path1 = "/System/a/b/a/b" and path2 = "a/b/a/b/c" the result is "/System/a/b/a/b/a/b/c". You can change LastOrDefault to FirstOrDefault to get "/System/a/b/a/b/c" instead.

请注意,该算法本质上创建了两条路径的所有可能组合,并不是特别有效.

Note that this algorithm essentially creates all possible combinations of the two paths and isn't particularly efficient.

这篇关于有没有一种简单的方法可以在 C# 中组合两个相对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆