Recipe 5.12. Displaying an Array's Data as a Delimited StringProblemYou have an array or type that implements ICollection, and you wish to display or store it as a string delimited by commas or some other delimiting character. This ability will allow you to easily save data stored in an array to a text file as delimited text. SolutionThe ConvertCollectionToDelStr method will accept any object that implements the ICollection interface. This collection object's contents are converted into a delimited string: public static string ConvertCollectionToDelStr(ICollection theCollection, char delimiter) { StringBuilder delimitedData = new StringBuilder(); foreach (string strData in theCollection) { if (strData.IndexOf(delimiter) >= 0) { throw (new ArgumentException( "Cannot have a delimiter character in an element of the array.", "theCollection")); } delimitedData.Append(strData).Append(delimiter); } // Return the constructed string minus the final // appended delimiter char. return (delimitedData.ToString().TrimEnd(delimiter)); } DiscussionThe following TestDisplayDataAsDelStr method shows how to use the Convert-CollectionToDelStr method to convert an array of strings to a delimited string: public static void TestDisplayDataAsDelStr( ) { string[] numbers = {"one", "two", "three", "four", "five", "six"} ; string delimitedStr = ConvertCollectionToDelStr(numbers, ','); Console.WriteLine(delimitedStr); } This code creates a delimited string of all the elements in the array and displays it as follows: one,two,three,four,five,six Of course, instead of a comma as the delimiter, you could also have used a semicolon, dash, or any other character. The delimiter type was made a char because it is best to use only a single delimiting character if you are going to use the String.Split method to restore the delimited string to an array of substrings. String.Split works only with delimiters that consist of one character. See AlsoSee the "ICollection Interface" topic in the MSDN documentation. |