开发者

How to aggregate IEnumerable<string> to string using Linq Aggregate function

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.

htt开发者_运维百科p://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/dac496c0-5b37-43ba-a499-bb8eff178706/

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.


You can just use String.Join for this. If you're using .NET4 then you can use the overload that takes an IEnumerable<string> directly:

string joined = string.Join(";", list);

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:

string joined = string.Join(";", list.ToArray());

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 a StringBuilder rather than multiple string allocations:

string joined = list.Aggregate(new StringBuilder(),
                               (sb, s) => sb.Append(s).Append(';'),
                               sb => (sb.Length > 0) ? sb.ToString(0, sb.Length - 1)
                                                     : "");


You can do it using below code

list.Aggregate((i, j) => i + ";" + j);


You'll need to provide an initializer, otherwise the first element will not have a ; added to it:

list.Aggregate<String>("", (x,y) => x + String.Format("{0};",y));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜