一步一步地拆分并连接字符串-C#Linq
这是我的字符串:一步一步地拆分并连接字符串-C#Linq,c#,linq,C#,Linq,这是我的字符串: 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/questio
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来实现这一点,您可以尝试使用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)));
具有副作用的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
如果没有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);
}
var str=“www.stackoverflow.com/questions/ask/user/end”;
string[]full=str.Split('/');
字符串结果=string.Empty;
for(int i=0;i
Linq无副作用;)Enumerable.Aggregate
如果我们使用List
作为结果,则可以在此处使用
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;
});
var raw=“www.stackoverflow.com/questions/ask/user/end”;
实际值=
原始分割(“/”)
.Aggregate(新列表(),
(列表,单词)=>
{
var combined=list.Any()?$“{list.Last()}/{word}”:word;
列表。添加(合并);
退货清单;
});
在这种情况下,我需要使用linq,而不是使用foreach@Nofuzy你有什么理由需要使用Linq?@Nofuzy如果你真的需要,这里有我最新的答案。事实上,linq.Select()
在幕后的作用与foreach
几乎相同,两者都迭代IEnumerable。在这种特殊情况下,在foreach
上使用Linq
是非常主观的。它与使用LINQ的版本稍有不同。为什么您不认为Aggregate
是合适的呢?我觉得很漂亮reasonable@Freggar:Aggregate
返回单个值,而不是IEnumerable
;使用Aggregate
可以解决这个问题,但是它在contextNice中是一个超调,没有副作用,Aggregate
你说的副作用是什么意思?@Nofuzy:changingprevior
变量,同时执行Linq querySo有什么问题?@Nofuzy:sideeffects(在摘录中混合查询和命令)使代码至少不那么可读,并且通常难以维护和调试(代码做了我们不期望的事情)。