如何聚合 IEnumerable使用 Linq Aggregate 函数转换为字符串
我有 Ienumerable
集合,我想将其连接成带有分隔符的单个字符串;
例如 {"一","二","三"} -> “一二三;”
可以使用以下函数吗?
List<string> list = new List<string>(){"One","Two","Three"};
list.Aggregate<String>((x,y) => x + String.Format("{0};",y));
我也尝试过这段代码:
list.Aggregate<String>((x,y) => String.Format("{0};{1}",x,y));
两个示例都不起作用。
编辑:我发现使用 Linq-2-sql 或 Linq-2-sql 中的聚合函数无法完成我想要的操作。
编辑2:我使用的解决方法是检查原始 linq 查询返回的项目...并将它们复制到新列表并按照以下答案中的建议在 linq 对象上进行连接,而不是linq-2-sql 对象。
I have Ienumerable<string>
collection that I want to concatenate into a single string with delimitor ;
for instance {"One","Two","Three"} -> "One;Two;Three;"
is it possible to do using the following function?
List<string> list = new List<string>(){"One","Two","Three"};
list.Aggregate<String>((x,y) => x + String.Format("{0};",y));
I have tried also this code:
list.Aggregate<String>((x,y) => String.Format("{0};{1}",x,y));
both samples didn't work.
EDIT: I see that it is not possible to do what I wanted using Linq-2-sql or Aggregate function in Linq-2-sql.
EDIT2: the workaround I used is to go over the items returned by the original linq query...and copies them to a new list and do the join as suggested in the answers below on a linq object and not linq-2-sql object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您只需使用
String.Join
即可这。如果您使用的是 .NET4,则可以使用 需要的重载直接 IEnumerable
:如果您使用的是旧版本的框架,那么您需要使用 采用
string[]
数组 代替的重载,如有必要,请先将集合转换为数组:编辑...
当然,如果您出于某种原因确实想使用
Aggregate
,那么没有什么可以阻止您。如果是这样,通常建议使用StringBuilder
构建字符串,而不是使用多个字符串分配:You can just use
String.Join
for this. If you're using .NET4 then you can use the overload that takes anIEnumerable<string>
directly:If you're using an older version of the framework then you'll need to use the overload that takes a
string[]
array instead, converting your collection to an array first if necessary:EDIT...
Of course, if you really want to use
Aggregate
for some reason then there's nothing stopping you. If so, it's usually recommended to build your string using aStringBuilder
rather than multiple string allocations:您可以使用下面的代码来完成
You can do it using below code
您需要提供一个初始值设定项,否则第一个元素将不会添加
;
:You'll need to provide an initializer, otherwise the first element will not have a
;
added to it: