Monday, March 26, 2012

Creating a Comma Delimited String from an Array

Something I haven't done very often is work with delimiters. But now is a time where I do have to occasionally generate some sort of output from an array and return a comma delimited string from it.

Previously, I would loop through every element of the array, append the delimiter and a space for readability, then go back, and chop off the last two characters. I never did like this, and always thought there may be a better way.

String[] Color ={"Red", "Orange", "Yellow", "Green", "Indigo", "Blue", "Violet"};
StringBuilder loopedColor = new StringBuilder();
foreach (var theColor in Color)
loopedColor.Append(", ");

var returnedLoop = loopedColor.ToString().Substring(0, loopedColor.ToString().Length - 2);

Later I would find the function that takes care of it for me- String.Join();

String[] Color ={"Red", "Orange", "Yellow", "Green", "Indigo", "Blue", "Violet"};
var JoinedStatement = String.Join(", ", Color);

Cleaner, and I'm sure Microsoft has thought about it more than I have. Why re-invent the wheel?

No comments:

Post a Comment