Coder Perfect

Concatenating strings using LINQ

Problem

How do you write the old-school in the most efficient way:

StringBuilder sb = new StringBuilder();
if (strings.Count > 0)
{
    foreach (string s in strings)
    {
        sb.Append(s + ", ");
    }
    sb.Remove(sb.Length - 2, 2);
}
return sb.ToString();

…in LINQ?

Asked by tags2k

Solution #1

This response demonstrates how to utilize LINQ (Aggregate) to answer the question, however it is not designed for everyday use. Because this method does not employ a StringBuilder, it will perform poorly when dealing with really long sequences. Use String for ordinary code. As in the previous response, join as shown.

Utilize aggregate queries such as 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 returns a scalar value from a set of values. T-SQL examples 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.

Keep in mind that aggregate queries are run right away.

MSDN: Aggregate Queries has more information.

If you must use Aggregate, use the StringBuilder variant offered in a comment by CodeMonkeyKing, which is roughly the same code as normal String. Include good performance for a big number of objects in your membership:

 var res = words.Aggregate(
     new StringBuilder(), 
     (current, next) => current.Append(current.Length == 0? "" : ", ").Append(next))
     .ToString();

Answered by Jorge Ferreira

Solution #2

return string.Join(", ", strings.ToArray());

There is a new overload for string in.Net 4. This is a join that accepts IEnumerableString> as a parameter. The code would then be as follows:

return string.Join(", ", strings);

Answered by Amy B

Solution #3

Why use Linq?

string[] s = {"foo", "bar", "baz"};
Console.WriteLine(String.Join(", ", s));

That works flawlessly and, as far as I recall, takes any IEnumerablestring>. There’s no need to aggregate anything here because it’ll take a long time.

Answered by Armin Ronacher

Solution #4

Have you taken a look at the Aggregate method?

var sa = (new[] { "yabba", "dabba", "doo" }).Aggregate((a,b) => a + "," + b);

Answered by Robert S.

Solution #5

Here’s a real-life example from my code:

return selected.Select(query => query.Name).Aggregate((a, b) => a + ", " + b);

A query is an object that has a Name property which is a string, and I want the names of all the queries on the selected list, separated by commas.

Answered by Daniel Earwicker

Post is based on https://stackoverflow.com/questions/217805/using-linq-to-concatenate-strings