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

How Can LINQ Efficiently Concatenate Strings in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-03 12:55:39560browse

How Can LINQ Efficiently Concatenate Strings in C#?

Concatenating Strings with LINQ

When dealing with collections of strings, there are often scenarios where we need to concatenate them into a single string. Traditionally, we would accomplish this using the StringBuilder class. However, with the advent of LINQ, we now have a more concise and expressive way to handle this task.

LINQ Aggregate Approach

LINQ provides the Aggregate method, which can be used for aggregating a sequence of values into a single result. To concatenate strings using Aggregate, we can employ the following steps:

  1. Initialize an empty string as the starting point.
  2. Iterate over the string collection, appending each string to the accumulator string, separated by a desired delimiter.
  3. Specify the final result as the accumulated string.

Code Example:

string[] words = { "one", "two", "three" };
var res = words.Aggregate(
    "", (current, next) => current + ", " + next);
Console.WriteLine(res);

This code produces the output:

, one, two, three

Other LINQ Options

While the Aggregate method can be used for string concatenation, it is not the most optimal approach. For better performance and readability, consider using the String.Join method instead:

string res = String.Join(", ", words);
Console.WriteLine(res);

The above is the detailed content of How Can LINQ Efficiently Concatenate Strings in C#?. 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