StringBuilder related question
I have written a program for a stack. (https://stackoverflow.com/questions/2617367?tab=votes#tab-top) For this i needed a StringBuilder to be able to show me what was in the stack else i would get the class name instead of the actual values inside.
My question is there any other way except for a StringBuilder for such kind of problem?
Also in what other kind of cases does this kind of problem happen? Also the way i have written the StringBuilder felt very awkward when i needed several things on 1 line. public override string ToString()
{
StringBuilder builder = new StringBuilder();
foreach (int value in tabel)
{
builder.Append(value);
builder.Append(" ");
}
if (tabel.Length == tabel.Length) // this is a bit messy, since I couldn't append after the rest above
{
builder.Append("(top:");
builder.Append(top);开发者_StackOverflow社区
builder.Append(")");
}
return builder.ToString();
}/*ToString*/
You could use Array.ConvertAll and String.Join instead of iterating the list yourself.
Also, when you talk about multiple things on one line... you don't have any linebreaks anywhere.
Or, if you keep using StringBuilder, the Append method returns the StringBuilder so you can chain calls together:
sb.Append("(top: ").Append(top).Append(")").AppendLine();
You could use an extension method like this to summarize enumerable collections
/// <summary>
/// A better ToString for Enumerable objects (mostly for logging)
/// </summary>
public static string ToStringList(this IEnumerable<string> collection, int limit)
{
return string.Join(", ", collection.Take(limit));
}
Usage
string result = tabel.Select(x => x.ToString()).ToStringList(50);
PS If you are using .NET prior to version 4 you might need a .ToArray() in there to satisfy string.Join()
Or, better yet, using the overload: string Join<T>(string separator, IEnumerable<T> values);
you can simplify to:-
/// <summary>
/// A better ToString for Enumerable objects (mostly for logging)
/// </summary>
public static string ToStringList<T>(this IEnumerable<T> collection, int limit)
{
return string.Join(", ", collection.Take(limit));
}
Usage
string result = tabel.ToStringList(50);
This is the correct use of a string builder (although your code looks buggy)
Note you can use AppendLine if you want a link break instead of using spaces.
You can also use AppendFormat which is the equivalent of string.format eg
builder.AppendFormat("(top:{0})", value);
ToString() overrides like this for a collection class rarely work out well in practice. They don't behave well when you've got thousands of elements in the collection. A decent visualization is to display the top element and the number of elements. For example:
public override string ToString() {
if (this.Count == 0) return "Empty";
else return string.Format("Top:{0}, Count:{1}", top, Count);
}
精彩评论