I have a loop where i create some string value based on certain conditions. I did place StringBuilder object outside of the loop and each time i have new row in loop i need to clear StringBuilder appended values for this row.
How do i clear those?
StringBuilder sb = new StringBuilder();
foreach (DataRow row in recipientsList.Rows)
{
sb.Length = 0;
sb.Append("<ul>");
if (row["needsToActivate"] == "1")
{
sb.AppendFormat("<li>{0}</li>", getUsersWithoutActivationTemplate());
}
if (row["needsToEnterSite"] == "1")
{
sb.AppendFormat("<li>{0}</li>", getUsersWithoutEnteringWebsiteForTwoWeeksTemplate());
}
if (row["needsPicture"] == "1")
{
sb.AppendFormat("<li>{0}</li>", getUsersWithoutPicturesTemplate());
}
if (row["needsText"] == "1")
{
sb.AppendFormat("<li>{0}</li>", getUsersWithoutTextTemplate());
}
if (row["needsCharacteristic"] == "1")
{
sb.AppendFormat("<li>{0}</li>", getUsersWithoutCharateristicsTemplate());
}
if (row["needsHobby"] == "1")
{
sb.AppendFormat("<li>{0}</li>", getUsersWithoutHobbiesTemplate());
}
sb.Append("</ul>");
}
Code with accepted answer;
You should use sb. delete(0, sb. length()) or sb. setLength(0) and NOT create a new StringBuilder().
Check if StringBuilder Is Empty Using the Length Property The StringBuilder class has a property named Length that shows how many Char objects it holds. If Length is zero that means the instance contains no characters.
Fortunately, you don't need to use StringBuilder anymore - the compiler can handle it for you. String concatenation has always been a well-discussed topic among Java developers. It's been costly.
C# StringBuilder is similar to Java StringBuilder. A String object is immutable, i.e. a String cannot be changed once created. Every time when you use any of the methods of the System. String class, then you create a new string object in memory.
You can simply;
sb.Length = 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With