我有一个字符串列表,我想将它们作为带有分号分隔符的字符串转储出来.
IEnumerable<string> foo = from f in fooList
where f.property == "bar"
select f.title;
Run Code Online (Sandbox Code Playgroud)
我现在要输出这个:
title1;title2;title3;title4
Run Code Online (Sandbox Code Playgroud)
我怎么做?
zel*_*lio 10
使用LINQ而不是String.Join就是这样的要求.虽然真的String.Join
可能是一个更安全/更容易的赌注.
IEnumerable<string> foo = from f in fooList
where f.property == "bar"
select f.title;
string join = foo.Aggregate((s, n) => s + ";" + n);
Run Code Online (Sandbox Code Playgroud)
string result = string.Join(";", fooList.Where(x=>x.property == "bar").Select(x=>x.title));
Run Code Online (Sandbox Code Playgroud)
从.NET 2.0开始,string类提供了方便的Join方法。虽然它最初仅在数组上运行,但 .NET 4 添加了 IEnumerable 重载...
IEnumerable<string> foo = from f in fooList
where f.property == "bar"
select f.title;
Console.WriteLine(string.Join(";", foo));
Run Code Online (Sandbox Code Playgroud)