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

标签 c# asp.net arrays string split

我正在构建自定义面包屑,我希望每个 LinkBut​​ton 都有唯一的 commandArgument url。

我有一个通用字符串变量,它是一个 url。每个子站点的名称可以不同,只要层次不限即可。

String 变量可能如下所示:

http://site/org/content/Change/Book/process/item

我想做的是拆分字符串变量并将其添加到数组中,如下所示:

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

我试过以下代码:

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

但它并不像我希望的那样。

任何形式的帮助都是适用的

最佳答案

您可以为此使用扩展方法和一些 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 中的结果:

enter image description here

关于c# - 如何剪切包含 url 的字符串并将其添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22631482/

相关文章:

C# 套接字 : synchronous calls within asynchronous ones

c# - C# 中左侧操作数的三元条件运算符

C# IndexOf,当单词是另一个单词的一部分时,如何?

c# - 如何处理 Telerik RadGrid 中的空值(在列中)? (替换为 HTML)

c# - Internet Explorer 在保存/打开文件时显示乱码?

c# - 大量物体的碰撞检测

asp.net - 如何访问嵌套母版页内的控件?为什么它的行为与内容页面不同?

android - Volley jsonArray 请求不工作

javascript - 给定一个递增整数数组 : How do you return a range for every three or more consecutive integers?

php - 将数据从 1 个数组添加到另一个