Using LINQ Aggregate Method to concatenate strings to delimited string

By Peter Bromberg

The LINQ Aggregate extension method is very powerful. However, there can be performance issues on very large datasets, in which case the use of StringBuilder may be preferable.

// Create a list of string items and populate it
List
<String> CheckedItems = new List<String>();
for( int i=0;i<10;i++)
CheckedItems.Add("test"+i.ToString() );

// Concatenate the List into a comma-delimited CSV style string
var    retval = CheckedItems.Aggregate(String.Empty, (current, s) => current + (s.Trim() + ",")).TrimEnd(",".ToCharArray());
Console
.WriteLine(retval);

//output:  test0,test1,test2,test3,test4,test5,test6,test7,test8,test9

Using LINQ Aggregate Method to concatenate strings to delimited string  (1477 Views)