Concatenating Strings with LINQ
The traditional method of concatenating strings involves using a StringBuilder and appending each string within a loop. However, for a more efficient approach, LINQ offers aggregate queries.
An aggregate query is a function that takes a collection of values and returns a scalar value. Using the dot-notation, you can call an aggregate query on an IEnumerable object.
To concatenate strings with LINQ, you can use the Aggregate method as follows:
string[] words = { "one", "two", "three" }; string res = words.Aggregate( "", // Start with an empty string for empty list handling (current, next) => current + ", " + next);
This code generates the following output:
, one, two, three
It's important to note that aggregate queries are executed immediately. For optimal performance with large sequences, consider using String.Join instead.
Alternatively, if you desire to use Aggregate, you can leverage a StringBuilder for improved performance:
var res = words.Aggregate( new StringBuilder(), (current, next) => current.Append(current.Length == 0? "" : ", ").Append(next));
The above is the detailed content of How Can LINQ's Aggregate Method Be Used for Efficient String Concatenation?. For more information, please follow other related articles on the PHP Chinese website!