如何剪切包含url的字符串并将其添加到数组中

Obs*_*vus 4 c# asp.net arrays string split

我正在构建一个自定义的痕迹,我想要每个LinkBut​​ton唯一的commandArgument url.

我有一个通用的字符串变量,它是一个url.每个子网站的名称可以是不同的,并且尽可能地不限制hierchy.

String变量可能如下所示:

http://site/org/content/Change/Book/process/item
Run Code Online (Sandbox Code Playgroud)

我想要做的是拆分字符串变量并将其添加到数组,所以它看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

我试过以下代码:

 private void AddBreadCrumb(SPWeb web)
    {
     var webUrl = web.Url;
     var linkList = new List<string>(webUrl.Split('/'));
     // etc..
    }
Run Code Online (Sandbox Code Playgroud)

但它并不像我希望它那样做.

适用任何形式的帮助

Sel*_*enç 9

你可以使用扩展方法和一些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;
}
Run Code Online (Sandbox Code Playgroud)

这是用法:

string url = "http://site/org/content/Change/Book/process/item";
var parts = url.ParseUrl();
Run Code Online (Sandbox Code Playgroud)

结果LINQPad:

在此输入图像描述

  • `yield` 关键字的使用将避免分配结果列表。 (2认同)