Using LINQ to concatenate strings
This answer shows usage of LINQ (Aggregate
) as requested in the question and is not intended for everyday use. Because this does not use a StringBuilder
it will have horrible performance for very long sequences. For regular code use String.Join
as shown in the other answer
Use aggregate queries like this:
string[] words = { "one", "two", "three" };
var res = words.Aggregate(
"", // start with empty string to handle empty list case.
(current, next) => current + ", " + next);
Console.WriteLine(res);
This outputs:
, one, two, three
An aggregate is a function that takes a collection of values and returns a scalar value. Examples from T-SQL include min, max, and sum. Both VB and C# have support for aggregates. Both VB and C# support aggregates as extension methods. Using the dot-notation, one simply calls a method on an IEnumerable object.
Remember that aggregate queries are executed immediately.
More information - MSDN: Aggregate Queries
If you really want to use Aggregate
use variant using StringBuilder
proposed in comment by CodeMonkeyKing which would be about the same code as regular String.Join
including good performance for large number of objects:
var res = words.Aggregate(
new StringBuilder(),
(current, next) => current.Append(current.Length == 0? "" : ", ").Append(next))
.ToString();
return string.Join(", ", strings.ToArray());
In .Net 4, there's a new overload for string.Join
that accepts IEnumerable<string>
. The code would then look like:
return string.Join(", ", strings);
Why use Linq?
string[] s = {"foo", "bar", "baz"};
Console.WriteLine(String.Join(", ", s));
That works perfectly and accepts any IEnumerable<string>
as far as I remember. No need Aggregate
anything here which is a lot slower.
Have you looked at the Aggregate extension method?
var sa = (new[] { "yabba", "dabba", "doo" }).Aggregate((a,b) => a + "," + b);