Wednesday 1 June 2011

Linq: Aggregate string array to string

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)

  1. First argument is the seed : use a StringBuilder
  2. Second argument is the cumulation function : use a delegate that appends each string in the enumerable to the StringBuilder.
  3. 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:

Anonymous said...

String.Join(",", parts);

He he !