Linq 的聚合函数,如何创建 CSV 字符串
我想使用 Linq 的聚合函数创建一个逗号分隔的值字符串。有人知道该怎么做吗?
给定一个像这样的字符串数组:
var authors = new string[] {"author 1", "author 2", "author 3"};
如何获得像这样的单个字符串 author 1,author 2,author 3? 我想像 authors.Aggregate(author =>author + ",")
这样的东西可能能够做到这一点,但不确定。
有想法吗?
I'd like to make a comma seperated value string with Linq's Aggregate function. Anyone know how to do this?
Given an array of strings like this:
var authors = new string[] {"author 1", "author 2", "author 3"};
How do I get a single string like this author 1, author 2, author 3?
I'm thinking something like authors.Aggregate(author => author + ",")
might be able to do this but not sure.
Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只想用逗号分隔它们,只需使用 string.Join:
这适用于任何 IEnumerable(至少在 .NET 4.0 中),但从 1.0 开始就使用字符串数组。
If you're only looking to comma-separate them, just use string.Join:
This will work with any IEnumerable<string> (at least in .NET 4.0), but has worked with arrays of strings since 1.0.
正如 Bennor McCarthy 所说,为此目的使用 string.Join 会更好。如果您确实想使用 Enumerable.Aggregate,则应该这样做:
这大致相当于:
As Bennor McCarthy says, you'd be much better off using
string.Join
for this purpose. If you really do want to useEnumerable.Aggregate
though, this should do:This is roughly equivalent to: