我怎么能砍包含URL字符串,并将其添加到阵列 [英] How can I cut a string that contains a url and add it to array
问题描述
我建立做一个自定义的痕迹,我想每个LinkButton的独特commandArgument网址。
I am building doing a custom breadcrumb and I want to each LinkButton unique commandArgument url.
我有一个通用的字符串变量是一个URL。每个子网站的名称可以是不同的,并且尽可能长的hierchy没有限制。
I have a generic string variable that is a url. The name of each subweb can be different and as long as possible the hierchy is not limited.
字符串变量可能是这样的:
the String variable could look like this:
http://site/org/content/Change/Book/process/item
我想这样做是为了分割字符串变量,它,所以它看起来像这样添加到一个数组:
what I would like to do is to split the string variable and add it to a array so it looks like this:
http://site/org
http://site/org/content/
http://site/org/content/Change/
http://site/org/content/Change/Book/
http://site/org/content/Change/Book/process/
http://site/org/content/Change/Book/process/item
我曾尝试以下code:
I have tried following code:
private void AddBreadCrumb(SPWeb web)
{
var webUrl = web.Url;
var linkList = new List<string>(webUrl.Split('/'));
// etc..
}
但它不喜欢做我想做的事情。
But it doesnt do like I want it to do.
任何形式的帮助是appriacted
Any kind of help is appriacted
推荐答案
您可以使用扩展方法对于有的 LINQ
:
You can use an extension method for that and some LINQ
:
public static IEnumerable<string> ParseUrl(this string source)
{
if(!Uri.IsWellFormedUriString(source, UriKind.Absolute))
throw new ArgumentException("The URI Format is invalid");
var index = source.IndexOf("//");
var indices = source.Select((x, idx) => new {x, idx})
.Where(p => p.x == '/' && p.idx > index + 1)
.Select(p => p.idx);
// Skip the first index because we don't want http://site
foreach (var idx in indices.Skip(1))
{
yield return source.Substring(0,idx);
}
yield return source;
}
下面是用法:
string url = "http://site/org/content/Change/Book/process/item";
var parts = url.ParseUrl();
在结果 LINQPad
:
这篇关于我怎么能砍包含URL字符串,并将其添加到阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!