这是我的字符串:
www.stackoverflow.com/questions/ask/user/end
我将其与/
分成一个单独的单词列表:myString.Split('/').ToList()
输出:
www.stackoverflow.com
questions
ask
user
end
我需要重新加入字符串以获得这样的列表:
www.stackoverflow.com
www.stackoverflow.com/questions
www.stackoverflow.com/questions/ask
www.stackoverflow.com/questions/ask/user
www.stackoverflow.com/questions/ask/user/end
我认为linq聚合但似乎它不适合这里。我想通过linq
完成所有这些答案 0 :(得分:13)
您可以尝试使用foreach迭代它
var splitted = "www.stackoverflow.com/questions/ask/user/end".Split('/').ToList();
string full = "";
foreach (var part in splitted)
{
full=$"{full}/{part}"
Console.Write(full);
}
或者使用linq:
var splitted = "www.stackoverflow.com/questions/ask/user/end".Split('/').ToList();
var list = splitted.Select((x, i) => string.Join("/", a.Take(i + 1)));
答案 1 :(得分:7)
Linq :
string prior = null;
var result = "www.stackoverflow.com/questions/ask/user/end"
.Split('/')
.Select(item => prior == null
? prior = item
: prior += "/" + item)
.ToList();
让我们把它打印出来
Console.WriteLine(string.Join(Environment.NewLine, result));
结果:
www.stackoverflow.com
www.stackoverflow.com/questions
www.stackoverflow.com/questions/ask
www.stackoverflow.com/questions/ask/user
www.stackoverflow.com/questions/ask/user/end
答案 2 :(得分:4)
Linq没有副作用;)
如果我们使用Enumerable.Aggregate
作为结果,则可以在此使用List<T>
。
var raw = "www.stackoverflow.com/questions/ask/user/end";
var actual =
raw.Split('/')
.Aggregate(new List<string>(),
(list, word) =>
{
var combined = list.Any() ? $"{list.Last()}/{word}" : word;
list.Add(combined);
return list;
});
答案 3 :(得分:0)
没有Linq写下代码,
var str = "www.stackoverflow.com/questions/ask/user/end";
string[] full = str.Split('/');
string Result = string.Empty;
for (int i = 0; i < full.Length; i++)
{
Console.WriteLine(full[i]);
}
for (int i = 0; i < full.Length; i++)
{
if (i == 0)
{
Result = full[i];
}
else
{
Result += "/" + full[i];
}
Console.WriteLine(Result);
}