"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can LINQ's Aggregate Method Be Used for Efficient String Concatenation?

How Can LINQ's Aggregate Method Be Used for Efficient String Concatenation?

Posted on 2025-02-06
Browse:365

How Can LINQ's Aggregate Method Be Used for Efficient String Concatenation?

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));
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3