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

How Can LINQ Efficiently Concatenate Strings in C#?

Susan Sarandon
Release: 2025-01-03 12:55:39
Original
597 people have browsed it

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);
Copy after login

This code produces the output:

, one, two, three
Copy after login

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);
Copy after login

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 of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template