Just a quick question.
I have a list collection = David, Bob, Ted
foreach (var value in collection)
{
sb.Append(value);
sb.Append(",");
}
sb.ToString().TrimEnd(',');
Output: David, Bob, Ted,
However when I try to trim off "," for the last value
sb.ToString().TrimEnd(',');
It still appears when I run it. Am I doing anything wrong?
Strings are immutable you are always creating a copy with a change and you are not using your new copy hens you do not see the change. To fix it use your copy of a string:
var result = sb.ToString().TrimEnd(',');
or modify string builder itself before calling ToString()
:
sb.Length--;
var result = sb.ToString();