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.
You can just use
String.Joinfor 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
Aggregatefor some reason then there’s nothing stopping you. If so, it’s usually recommended to build your string using aStringBuilderrather than multiple string allocations: