Home >Backend Development >C++ >How Can LINQ Efficiently Concatenate Strings?
In older code, strings were often concatenated using a StringBuilder in a loop. This method, while functional, can be inefficient and verbose.
LINQ offers a more concise and efficient alternative through aggregate queries. To concatenate strings using LINQ, follow these steps:
Aggregate queries are used to reduce a collection of values into a single scalar value. In this case, the strings will be reduced to a single, concatenated string.
string[] words = { "one", "two", "three" }; var result = words.Aggregate( "", // Start with an empty string to handle empty lists. (current, next) => current + ", " + next);
Executing this query outputs:
one, two, three
While aggregate queries are a versatile LINQ feature, String.Join offers a more performant option for concatenating large numbers of strings:
string result = String.Join(", ", words);
The above is the detailed content of How Can LINQ Efficiently Concatenate Strings?. For more information, please follow other related articles on the PHP Chinese website!