Home >Backend Development >C++ >How Can LINQ Efficiently Concatenate Strings?

How Can LINQ Efficiently Concatenate Strings?

Barbara Streisand
Barbara StreisandOriginal
2025-01-04 05:53:40570browse

How Can LINQ Efficiently Concatenate Strings?

LINQ for Concatenating 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

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);

Breakdown

  • Aggregate: Starts the query, specifying an initial value and an aggregation function.
  • (current, next) => ...: Defines the aggregation function that combines each string with a delimiter into the current string.
  • current ", " next: Concatenates the delimiter and the next string to the current string.

Result

Executing this query outputs:

one, two, three

Alternative Using StringBuilder

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn