Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ to concatenate strings

What is the most efficient way to write the old-school:

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?

like image 589
tags2k Avatar asked Oct 20 '08 08:10

tags2k


People also ask

How do you concatenate in Linq?

In LINQ, the concatenation operation contains only one operator that is known as Concat. It is used to append two same types of sequences or collections and return a new sequence or collection. It does not support query syntax in C# and VB.NET languages. It support method syntax in both C# and VB.NET languages.

How do I concatenate a list of strings?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

How do you combine strings in Java?

In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java. lang. String class.


1 Answers

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(); 
like image 191
Jorge Ferreira Avatar answered Oct 01 '22 13:10

Jorge Ferreira