将 string[] 转换为字符串而不使用 foreach
string x;
foreach(var item in collection)
{
x += item+",";
}
我可以用 lambda 写这样的东西吗?
string x;
foreach(var item in collection)
{
x += item+",";
}
can I write something like this with lambdas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
假设使用 C#,您尝试过 String.Join() 吗? 或者是否必须使用 lambda?
示例:
编辑
虽然原始标题(和示例)是关于用分隔符连接字符串(在我看来,
String.Join()
做得最好),但原始海报似乎询问更广泛的解决方案:如何应用自定义格式的字符串列表。我的答案是编写你自己的方法。 String.Join 有一个目的,如其名称所示(连接一些字符串)。 您的格式逻辑很可能在您的项目中有意义,因此请编写它,给它一个适当的名称并使用它。
例如,如果您想为每个项目输出
,请进行如下操作:
我认为意图更清晰,而且您也不会受到性能影响在循环中连接字符串。
Assuming C#, have you tried String.Join()? Or is using lambdas mandatory?
Example:
EDIT
Although the original title (and example) was about concatenating strings with a separator (to which
String.Join()
does the best job in my opinion), the original poster seems to ask about the broader solution: how to apply a custom format a list of strings.My answer to that is write your own method. String.Join has a purpose, reflected by its name (joins some strings). It's high chance that your format logic has a meaning in your project, so write it, give it a proper name and use it.
For instance, if you want to output
<li>text</li>
for every item, make something as this:I think the intent is clearer, and you also don't take the performance hit of concatenating strings in a loop.
您对解决方案的寻找太过分了。
String
类有一个Join
方法来实现此目的:You are looking too far for the solution. The
String
class has aJoin
method for this:更短的语法,感谢 Earwicker
Shorter syntax, thanks to Earwicker
这回答了你的问题了吗?
连接字符串的最有效方法?
请注意,您可以这样做与
Aggregate
一样,但内置的string.Join
对于长数组来说更易于使用且速度更快。Does this answer your question?
Most efficient way to concatenate strings?
Note that you can do this with
Aggregate
, but the built-instring.Join
is both easier to use and faster for long arrays.