Question:
I want to concatenate all strings of an array using Linq. How to?How to use the aggregate method with enumerables of string?
Answer:
You can use the Aggregate method of the IEnumerable<string> (include using System.Linq)- First argument is the seed : use a StringBuilder
- Second argument is the cumulation function : use a delegate that appends each string in the enumerable to the StringBuilder.
- Third argument is the selector function: use a delegate that gets the result from the StringBuilder.
Here is the sample code
string[] parts = new string[] {"eins","zwei","drei"}; System.Text.StringBuilder sb = new StringBuilder(); string inListString = parts.Aggregate( sb, (sum, part) => sum.AppendFormat("'{0}',", part), sum => sum.ToString().TrimEnd(',') ); Console.WriteLine(inListString);
1 comment:
String.Join(",", parts);
He he !
Post a Comment