Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder extension method for appending a collection in C#

In C#, I'm trying to build an extension method for StringBuilder called AppendCollection() that would let me do this:

var sb1 = new StringBuilder();
var sb2 = new StringBuilder();
var people = new List<Person>() { ...init people here... };
var orders = new List<Orders>() { ...init orders here... };

sb1.AppendCollection(people, p => p.ToString());
sb2.AppendCollection(orders, o => o.ToString());

string stringPeople = sb1.ToString();
string stringOrders = sb2.ToString();

stringPeople would end up with a line for each person in the list. Each line would be the result of p.ToString(). Likewise for stringOrders. I'm not quite sure how to write the code to make the lambdas work with generics.

like image 261
Lance Fisher Avatar asked Dec 09 '08 19:12

Lance Fisher


People also ask

Can StringBuilder append StringBuilder?

StringBuilder has a public StringBuilder append(CharSequence s) method. StringBuilder implements the CharSequence interface, so you can pass a StringBuilder to that method.

What is difference between append and AppendLine in StringBuilder C#?

Append: Appends information to the end of the current StringBuilder. AppendLine: Appends information as well as the default line terminator to the end of the current StringBuilder.

Why StringBuilder is used in C#?

StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

How does StringBuilder work C#?

The StringBuilder works by maintaining a buffer of characters (Char) that will form the final string. Characters can be appended, removed and manipulated via the StringBuilder, with the modifications being reflected by updating the character buffer accordingly. An array is used for this character buffer.


1 Answers

Use the Func<T,string> delegate.

public static void AppendCollection<T>(this StringBuilder sb, 
                                       IEnumerable<T> collection, Func<T, string> method) {
   foreach(T x in collection) 
       sb.AppendLine(method(x));
}
like image 192
mmx Avatar answered Sep 19 '22 18:09

mmx