如何使用带单引号的 Linq 聚合
假设我有一个字符串集合,如下所示:
IList<string> myList = new List<string>(){"one", "two", "three"};
使用 myList.Aggregate
我想以“'one', 'two', 'third'”(包括单引号)
结束有人有一种巧妙的方法来做到这一点,只使用聚合函数?我在想一些类似的事情
myList.Aggregate((increment, seed) => string.Concat(increment, ", ", seed));
,但这只是解决方案的一半。
Let's assume that I have a collection of strings, like so:
IList<string> myList = new List<string>(){"one", "two", "three"};
Using myList.Aggregate
I would like to end up with "'one', 'two', 'three'" (including single quotes)
Does someone have a sleak way of doing this, only using the Aggregate function? I was thinking something in the lines of
myList.Aggregate((increment, seed) => string.Concat(increment, ", ", seed));
but that's only half the solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有什么理由使用
Aggregate
而不是更简单的string.Join
?(如果您使用的是 .NET 3.5,请添加
ToArray
调用。)您可以使用
Aggregate
实现string.Join
> (理想情况下使用StringBuilder
),但这并不是很令人愉快。假设一个非空集合,我认为应该这样做:Any reason to use
Aggregate
rather than the simplerstring.Join
?(Add a
ToArray
call if you're using .NET 3.5.)You can implement
string.Join
usingAggregate
(ideally using aStringBuilder
) but it's not terribly pleasant. Assuming a non-empty collection, I think this should do it:既然您指定“仅使用聚合函数”,那么:(
或)
以这种方式使用聚合来进行字符串连接,效率确实很低。
编辑:更新以删除前导
,
。Since you specify "only using the Aggregate function", how about:
(or)
Using
Aggregate
in this manner for string concatenation is really inefficient though.EDIT: Updated to get rid of the leading
,
.